Cuestionario Ampliado del Censo de Población y Vivienda 2020

El cuestionario ampliado se guarda en un un archivo .RData.

data <- read_sav("~/Personas_Censo 2020.SAV")

save(data, 
      file = paste0(here::here(), "/Bases/Censo_Personas_2020.RData"))

Se seleccionan las variables que se desean conservar para la realización de este documento y se guarda en un archivo .RData para practicidad del manejo de datos.

Posibles variables que se pueden contemplar en la migración laboral

  • EDAD

  • SEXO

  • AFRODES

  • HLENGUA

  • QDIALECT_INALI

  • PERTE_INDIGENA

  • NIVACAD ¿Cuál fue el último año o grado aprobado por (NOMBRE) en la escuela?

  • ALFABET

  • SITUA_CONYUGAL

  • HIJOS_NAC_VIVOS

  • NIVACAD ¿Cuál fue el último año o grado aprobado por (NOMBRE) en la escuela?

  • CONACT Situación laboral

  • OCUPACION_C Cuál fue la ocupación de (NOMBRE) la semana pasada? Por ejemplo: técnico electricista, maestra de primaria, vendedora de frutas, albañil, mecánico de autos

  • SITTRA Situación de trabajo

  • VACACIONES

  • SERVICIO_MEDICO

  • INCAP_SUELDO

  • INGTRMEN

  • ACTIVIDADES_C ¿A qué se dedica el negocio, empresa o lugar donde trabajó (NOMBRE)? Por ejemplo: hacer muebles de madera, hacer escobas, reparar autos, vender ropa usada, armar televisores..

  • TIE_TRASLADO_TRAB

  • MED_TRASLADO_TRAB1

  • MED_TRASLADO_TRAB2

  • MED_TRASLADO_TRAB3

La variable mydata contiene 15 015 683 observaciones y 33 variables.

load(paste0(here::here(), "/Bases/Censo_Personas_2020.RData"))

mydata <- data %>%
           select(CVE_ENT, ENT, MUN, CVE_MUN, ENT_PAIS_TRAB, MUN_TRAB, CVE_MUN_TRABAJO, 
                  EDAD, SEXO, AFRODES, HLENGUA, QDIALECT_INALI, PERTE_INDIGENA, NIVACAD, ESCOLARI, ESCOACUM, ALFABET, 
                  CAUSA_MIG, SITUA_CONYUGAL, HIJOS_NAC_VIVOS, CONACT, OCUPACION_C, SITTRA, VACACIONES, 
                  SERVICIO_MEDICO, INCAP_SUELDO, INGTRMEN, ACTIVIDADES_C, TIE_TRASLADO_TRAB,  
                  MED_TRASLADO_TRAB1, MED_TRASLADO_TRAB2, MED_TRASLADO_TRAB3, FACTOR, ESTRATO, UPM)

save(mydata, file = paste0(here::here(), "/Bases/03_Movilidad laboral_2020.RData"))

✔️A partir de aquí se pueden correr los códidos 👇.
Se carga el archivo Migracion laboral_2020.RData.

load(file = paste0(here::here(), "/Bases/03_Movilidad laboral_2020.RData"))

# Para fines prácticos se genera un ponderador de uno 
mydata <- mydata %>% 
           select(CVE_ENT, ENT, MUN, CVE_MUN, ENT_PAIS_TRAB, MUN_TRAB, CVE_MUN_TRABAJO, 
                  CONACT, EDAD, FACTOR, ESTRATO, UPM) %>%
            mutate(M = 1)  %>%
             mutate(NOM_ENT = as.factor(.$CVE_ENT)) %>%
              ungroup()

Entidades

Se genera un vector con el nombre de las entidades llamado estados para facilitar los filtros en el documento.
Se genera un vector con las abreviaturas de las entidades llamado ent para fines prácticos.
Se genera un vector con las claves de los municipios, pero es importante hacer notar que tres municipios no entraron el muestreo del Cuestionario Ampliado.

# Claves de los estados
estados <- sjlabelled::get_labels(mydata$CVE_ENT)

nom_estados <- c( "Aguascalientes", "Baja California" ,"Baja California Sur", "Campeche", "Coahuila de Zaragoza", "Colima", 
                  "Chiapas", "Chihuahua", "Ciudad de México", "Durango", "Guanajuato", "Guerrero", "Hidalgo", "Jalisco",        
                  "México", "Michoacán de Ocampo", "Morelos", "Nayarit", "Nuevo León", "Oaxaca", "Puebla", "Querétaro", 
                  "Quintana Roo", "San Luis Potosí", "Sinaloa", "Sonora", "Tabasco", "Tamaulipas", "Tlaxcala", 
                  "Veracruz de Ignacio de la Llave", "Yucatán", "Zacatecas")

est <- c("AGS", "BC", "BCS", "CAMP", "COAH", "COL", "CHIS", "CHIH", "CDMX", "DGO", "GTO", "GRO", "HGO",
         "JAL", "MEX", "MICH", "MOR", "NAY", "NL", "OAX", "PUE", "QRO", "QROO", "SLP","SIN","SON", "TAB", 
         "TAMS", "TLX", "VER", "YUC", "ZAC")

# Claves de los municipios
MUN <- readRDS(paste0(here::here(), "/Bases/municipios_2020.RDS"))
nom_municipios <- sjlabelled::get_labels(MUN$NOM_MUN) %>% as.factor()
municipios <- sjlabelled::get_labels(MUN$CVE_MUN) %>% as.factor()

# Se le asignan las etiquetas a los nombres de los estados 
levels(mydata$NOM_ENT) <- estados

Población ocupada de 15 años y más

Se identifica a la población ocupada de 15 años y más.

filter((EDAD >= 15 & EDAD != 999) & (CONACT >= 10 & CONACT <= 20))'.

# Clave de los estados
tablas <- str_pad(rep(1:32), width = 3, pad = "0")

Pob.ocupada <- mydata %>%
                as.data.frame() %>%
                 mutate(EDAD = as.numeric(.$EDAD)) %>%
                  subset((EDAD >= 15 & EDAD <= 130) & (CONACT >= 10 & CONACT <= 20)) %>%
                   filter(CVE_MUN_TRABAJO %in% municipios)  # Filtro del lugar de trabajo dentro del país. 

Población ocupada de 15 años y más

Población economicámente activa de 15 años y más

Nivel estatal

Migración laboral

Se utiliza la paquetería survey para poder trabajar con la muestra del cuestionario ampliado, en la cual se selecciona a la población ocupada de 15 años y más.

options(survey.lonely.psu = "adjust")

MC <- mydata %>%
       as.data.frame() %>%
        mutate(EDAD = as.numeric(.$EDAD)) %>%
         subset((EDAD >= 15 & EDAD <= 130) & (CONACT >= 10 & CONACT <= 20)) %>%
          filter(ENT_PAIS_TRAB %in% estados) %>%
           svydesign(data = ., id = ~UPM, strata = ~ESTRATO, weight = ~FACTOR, nest = T)

saveRDS(MC, file = paste0(here::here(), "/Output/Estado/03_Movilidad laboral/2020/MC_estado.RDS"))

Se genera una matriz cruzada de migración laboral a nivel estatal, utilizando la función svytable de la paquetería survey.

MC <- readRDS(file = paste0(here::here(), "/Output/Estado/03_Movilidad laboral/2020/MC_estado.RDS"))

Migrantes <- svytable(~ENT_PAIS_TRAB + CVE_ENT, design = MC)

La función cross_cases() de la paquetería expss se utiliza para crear tablas de contingencia cruzadas a partir de dos o más variables categóricas. Utilizando el comando weight, permite ponderar las observaciones “factores de expansión” en la tabla.

Se quita la diagonal a la matriz cruadrada con la función diag.remove() de la paquetería sna, donde esta función reemplaza los elementos de la diagonal principal de una matriz por un valor nulo o por el valor especifico.

Migrantes <- Migrantes %>%
              as.data.frame() %>%
               expss::cross_cases(CVE_ENT, ENT_PAIS_TRAB, weight = Freq) %>%
                as.data.frame() %>%
                 slice(-33) %>% 
                  select(-row_labels) 

rownames(Migrantes)<- nom_estados
colnames(Migrantes) <- nom_estados

save(Migrantes, file = paste0(here::here(), "/Bases/Estado/03_Movilidad laboral/2020/Matriz de MTrab a nivel estatal 2020.RData"))

wb <- createWorkbook()
addWorksheet(wb, "MTrabajo 2020")
writeData(wb, 1, Migrantes, colNames = TRUE, rowNames = TRUE)
saveWorkbook(wb, file = paste0(here::here(), "/Bases/Estado/03_Movilidad laboral/2020/Matriz de MTrab a nivel estatal 2020.xlsx"), overwrite = TRUE)

Matriz de migración laboral a nivel estatal, 2020

Matriz de migración laboral, 2020
Nivel estatal
Entidad Aguascalientes Baja California Baja California Sur Campeche Coahuila de Zaragoza Colima Chiapas Chihuahua Ciudad de México Durango Guanajuato Guerrero Hidalgo Jalisco México Michoacán de Ocampo Morelos Nayarit Nuevo León Oaxaca Puebla Querétaro Quintana Roo San Luis Potosí Sinaloa Sonora Tabasco Tamaulipas Tlaxcala Veracruz de Ignacio de la Llave Yucatán Zacatecas
Aguascalientes 619583 67 0 0 90 132 5 105 892 26 696 10 4 2459 492 196 20 13 397 0 59 155 0 295 13 72 0 98 11 61 3 2072
Baja California 27 1703754 743 27 0 82 82 29 509 79 29 27 0 237 23 29 0 169 138 0 0 0 0 27 349 1669 0 7 0 128 0 0
Baja California Sur 0 285 369243 0 0 0 7 0 120 21 49 0 0 44 63 0 0 0 20 28 26 0 0 61 20 79 0 0 20 21 0 0
Campeche 12 0 18 376224 0 0 93 0 141 0 10 26 0 57 168 36 18 0 89 82 39 8 689 20 0 3 1165 31 24 264 3459 0
Coahuila de Zaragoza 87 142 26 16 1220652 85 4 534 440 12253 171 66 48 229 168 15 0 14 5088 54 253 217 2 153 27 299 24 684 0 14 4 727
Colima 54 121 30 27 43 336327 4 4 283 0 125 8 24 3418 166 1724 0 48 18 102 9 13 24 3 69 91 10 34 0 0 24 0
Chiapas 22 1110 57 1092 247 39 1830454 190 1787 49 185 130 44 2006 973 275 40 143 1252 1802 362 160 4118 283 336 3610 5370 217 6 776 569 40
Chihuahua 19 184 0 20 327 10 7 1578018 178 451 117 60 0 561 209 38 150 10 66 134 47 100 5 30 366 416 0 94 0 0 124 250
Ciudad de México 310 221 310 273 300 99 513 318 4180375 121 1498 614 2768 2019 182761 1435 3439 160 1325 1175 4042 2335 730 738 472 340 146 210 967 1378 460 293
Durango 182 111 68 109 30232 1 20 1480 190 648196 95 109 40 299 327 27 0 206 672 131 4 147 0 158 620 418 0 44 3 166 0 1526
Guanajuato 797 491 152 58 179 102 122 133 1413 240 2466652 84 219 3063 957 5002 61 50 626 150 463 30617 1 7954 183 661 72 362 53 250 77 224
Guerrero 21 311 617 60 41 123 41 120 2277 55 325 1281383 138 904 2971 2441 2504 154 153 361 691 272 97 26 1875 849 107 71 33 150 21 59
Hidalgo 126 280 152 215 981 132 153 222 28982 168 1066 359 1160677 2276 35413 634 474 71 2384 1003 2577 8067 92 1510 636 526 79 563 1388 2118 96 374
Jalisco 5464 508 135 101 190 3834 45 330 3417 301 5087 59 155 3639413 984 5014 173 8962 796 294 199 517 379 437 729 433 51 237 0 296 121 939
México 741 683 403 522 898 459 1163 1174 1306249 654 4354 2390 24590 5288 5585943 3759 5942 633 3336 2389 5479 20056 1888 1915 683 1013 466 879 2738 2745 263 602
Michoacán de Ocampo 314 220 22 48 19 430 10 76 2410 110 11552 2134 30 5847 4453 1877152 107 241 229 64 422 2290 49 153 103 152 120 88 75 161 22 110
Morelos 176 101 50 98 111 29 266 193 16623 28 285 1836 279 429 7107 88 849859 6 233 299 2592 559 165 82 125 124 46 83 109 304 6 21
Nayarit 1 322 71 50 5 13 44 7 156 81 125 0 1 10493 110 154 0 500300 84 317 21 9 12 22 569 176 5 39 3 20 0 62
Nuevo León 99 19 0 439 5051 6 175 194 1586 240 331 25 5 442 514 45 182 0 2457294 438 289 1557 182 1493 46 125 47 3635 7 358 13 389
Oaxaca 53 792 163 779 100 31 830 264 3032 63 565 688 159 571 2354 92 129 12 621 1539661 1896 328 147 245 553 2058 171 251 52 4631 68 40
Puebla 272 1920 474 495 327 230 625 579 19647 149 1457 1847 2335 2060 15024 450 2488 119 1706 3942 2567119 1690 459 564 364 2791 419 613 10399 11200 299 826
Querétaro 372 100 11 0 68 0 0 171 4517 0 8005 234 915 624 2264 554 131 4 752 795 347 1017122 35 362 147 55 103 154 0 283 28 56
Quintana Roo 5 117 6 290 0 0 186 10 252 0 0 0 0 196 381 0 75 14 7 159 14 10 852590 0 0 0 164 0 0 200 780 0
San Luis Potosí 284 93 37 52 711 31 13 57 678 104 1376 20 511 641 554 112 80 0 5665 130 550 770 86 1115675 610 97 80 1997 36 1614 30 1270
Sinaloa 16 704 300 648 29 119 92 848 514 857 190 99 19 720 102 105 6 532 117 47 4 78 37 107 1215400 2340 104 24 0 18 0 95
Sonora 18 2082 86 8 38 10 12 703 335 12 204 5 0 92 68 36 0 32 252 26 117 4 18 33 729 1209493 0 189 0 117 0 160
Tabasco 10 39 14 7202 207 31 5114 67 526 0 162 26 9 134 374 97 64 4 552 90 92 180 2119 13 0 155 878364 334 0 2020 415 53
Tamaulipas 63 22 29 1293 301 52 0 60 1080 0 52 60 146 378 306 105 82 24 4462 122 2161 168 128 1670 7 93 433 1439916 6 5364 40 134
Tlaxcala 65 135 92 65 177 35 134 136 6616 49 1063 150 1664 862 4824 157 411 30 591 251 47375 622 281 138 153 255 60 193 468949 793 49 37
Veracruz de Ignacio de la Llave 155 940 487 6593 722 263 706 631 10038 179 722 230 3173 1958 9111 283 369 93 3966 4309 8986 1344 1058 1231 971 2566 3026 17161 345 3049368 385 255
Yucatán 0 2 5 5419 28 7 284 15 2091 11 38 1 1043 129 615 114 109 0 302 16 31 12 18252 18 94 25 1060 8 1 318 994855 1
Zacatecas 7997 70 51 0 598 25 3 355 227 1103 474 124 5 1964 225 21 0 69 372 49 25 100 51 2300 528 127 2 58 0 16 3 568818
Fuente: Estimaciones del CONAPO.

Gráfico dinámico

Gráfico dinámico de migración laboral a nivel estatal.

load(file = paste0(here::here(), "/Bases/Estado/03_Movilidad laboral/2020/Matriz de MTrab a nivel estatal 2020.RData"))

tabla <- Migrantes %>%
          sna::diag.remove(remove.val = 0) 

names <- c("Aguascalientes", "Baja California" ,"Baja California Sur", "Campeche", "Coahuila", "Colima", 
           "Chiapas", "Chihuahua", "Ciudad de México", "Durango", "Guanajuato", "Guerrero", "Hidalgo", "Jalisco",    
           "México", "Michoacán", "Morelos", "Nayarit", "Nuevo León", "Oaxaca", "Puebla", "Querétaro", 
           "Quintana Roo", "San Luis Potosí", "Sinaloa", "Sonora", "Tabasco", "Tamaulipas", "Tlaxcala", 
           "Veracruz", "Yucatán", "Zacatecas")

# Paleta de colores
paleta <- rev(colorRampPalette(pals::ocean.matter(100))(32))

p <- chorddiag(tabla, 
               groupNames = names,
               groupColors = paleta, 
               groupnamePadding = 10, 
               #height = 700, 
               #width = 700,
               margin = 120,
               groupThickness = 0.07,
               groupPadding = 3,
               groupnameFontsize = 12,
               fadeLevel = '0.1',
               tickInterval = seq(0, 500000, 10000),
               chordedgeColor = "transparent",
               showZeroTooltips = FALSE,
               showTicks = TRUE)

# Ajusta las etiquetas usando JavaScript para modificar su posición
p <- htmlwidgets::onRender(p, '
      function(el, x) {
        d3.selectAll(".group text")
          .attr("text-anchor", "middle")
          .attr("dx", "0")  
          .attr("dy", "0.75em"); 
      }
')

# Crear un contenedor div y aplicar estilos CSS para centrarlo
#p <- tags$div(style = "display: flex; justify-content: center; align-items: center;", p)

p
p %>% 
 mapshot(url = paste0(here::here(),"/images/MTrab_2020.html"))

#htmlwidgets::saveWidget(p, paste0(here::here(), "/Graficos/Estado/03_Movilidad laboral/2020/MTrab a nivel estatal 2020.html"), selfcontained = TRUE)
#require(webshot)
#webshot(url = paste0(here::here(), "/Graficos/Estado/03_Movilidad laboral/2020/MTrab a nivel estatal 2020.html"),
 #         file = paste0(here::here(), "/Graficos/Estado/03_Movilidad laboral/2020/MTrab a nivel estatal 2020.png"),
  #                cliprect = "viewport")

Gráficos migración laboral

ChordDiagram

load(file = paste0(here::here(), "/Bases/Estado/03_Movilidad laboral/2020/Matriz de MTrab a nivel estatal 2020.RData"))

tabla <- Migrantes %>%
          sna::diag.remove(remove.val = 0)  

rownames(tabla) <- stringr::str_wrap(nom_estados, 100)
colnames(tabla) <- stringr::str_wrap(nom_estados, 100)

# Paleta de colores
#paleta <- colorRampPalette(pals::ocean.matter(100))(50)
paleta <- colorRampPalette(c("#230A3A", "#250A3A", "#2E1047", "#2A004D", "#3B004D", "#4D004B", "#501551", "#550252", "#660762", "#7D1D6B", "#871D62","#952664", "#A6236C",  "#AF3766", "#AE2A5E", "#B53C52", "#C33B5D", "#CA3F56", "#D24949", "#DB5854", "#DE5435", "#E45B2F", "#E86328", "#ED6B21", "#ED8861", "#F4A472", "#EBB56B", "#ECC763", "#E8B94B", "#D4A432"))(50)

tabla2 <- color_chord_diagram(tabla1 = tabla, paleta)
file = "/Graficos/Estado/03_Movilidad laboral/2020/ChordDiagram de MTrab a nivel estatal.pdf"

## Gráficos a nivel estatal 
chord_diagram_graph(file = file, 
                    width = 7, 
                    height = 7, 
                    family = "Montserrat Medium", 
                    paleta = paleta, 
                    tabla1 = tabla, 
                    tabla2 = tabla2, 
                    color_labels = "#170A3A",
                    transparency = 0.4,
                    circo.text = 9,
                    circos.axis.text = 6,
                    adj.text =c(-0.05, 0.5), #Ajuste de las etiquetas (x, y)
                    adj.ylim = 0.1,
                    gap.degree = 2, 
                    clock.wise = FALSE,
                    track.margin = c(-0.07, 0.1),
                    margin = rep(0, 4))
Gráficos por estados

Se filtran los flujos migratorios que son exclusivos de los estados y que visualmente sean más interpretables.

load(file = paste0(here::here(), "/Bases/Estado/03_Movilidad laboral/2020/Matriz de MTrab a nivel estatal 2020.RData"))

tabla <- Migrantes %>%
          sna::diag.remove(remove.val = 0) 

rownames(tabla) <- stringr::str_wrap(nom_estados, 100)
colnames(tabla) <- stringr::str_wrap(nom_estados, 100)

# Nombre de los estados 
estado <- stringr::str_wrap(nom_estados, 100)

filtro_est <- Migrantes %>%
               as.data.frame() %>%
                tibble::rownames_to_column(var = "rn") %>% 
                 melt(., id.vars = "rn", variable.name = "cn") %>%
                  mutate_if(is.factor, as.character) 

### Sacar el promedio de los flujos migratiorios para determinar como se van a grupar los estados 
#### Es importante correr la tabla1[[x]] sin filtros para determinar el número promedio de flujos de migración
#### Filtro <<<<< filter(value > 0 & rn != estado[x]) %>%
#filtro_mig <- sapply(1:32, function(x)
 #                     mean(tail(sort(tabla1[[x]]), 1), na.rm = TRUE))
#p <- data.frame(estados = est,
 #               filtro_estados = filtro_mig)
#write.xlsx(p, file = paste0(here::here(), "/Bases/Estado/03_Movilidad laboral/2020/Filtro a nivel estatal.xlsx"))

filtro_mig <- read.xlsx(paste0(here::here(), "/Bases/Estado/03_Movilidad laboral/2020/Filtro a nivel estatal.xlsx"), colNames = TRUE) %>% 
               pull(filtro_estados)

tabla1 <- migration_flows_states(tabla = tabla, 
                                 filtro_mig = filtro_mig, 
                                 filtro_est = filtro_est, 
                                 category = estado, 
                                 group = "Otro estados")

## Se guardan las matrices de movilidad laboral para analizarlos después. 
wb <- createWorkbook()
for(i in 1:32){
     tabla <- tabla1[[i]] %>%
                as.data.frame() %>%
                 adorn_totals(c("row", "col"), 
                               fill = "-", 
                                na.rm = TRUE, 
                                 name = "Total",,,,contains(colnames(tabla1[[i]])))
                 
     addWorksheet(wb, paste(est[i]))
     writeData(wb, i, tabla, colNames = TRUE, rowNames = TRUE)
     saveWorkbook(wb, 
                  file = paste0(here::here(), "/Output/Estado/03_Movilidad laboral/2020/Matriz MTrab por estados_2020_Reduccion.xlsx"), 
               overwrite = TRUE)
}
saveRDS(tabla1, file = paste0(here::here(), "/Output/Estado/03_Movilidad laboral/2020/Tabla MTrab por estados.RDS"))
tabla1 <- readRDS(file = paste0(here::here(), "/Output/Estado/03_Movilidad laboral/2020/Tabla MTrab por estados.RDS"))

total_tablas <- totales(tabla1 = tabla1, 
                        Clave = "CVE_ENT", 
                        Inmigrantes = "Salen por trabajo",  
                        Emigrantes = "Entran por trabajo")

porcentajes_tablas <- porcentajes(tabla1 = tabla1, 
                                  Clave = "CVE_ENT", 
                                  Inmigrantes = "%Salen por trabajo",  
                                  Emigrantes = "%Entran por trabajo")

# Se guardan los totales de las matrices reducidas 
wb <- createWorkbook()
for(i in 1:32){
     addWorksheet(wb, paste(est[i]))
     writeData(wb, i, totales_tablas[[i]], colNames = TRUE, startCol = 1)
     writeData(wb, i, porcentajes_tablas[[i]], colNames = TRUE, startCol = 5)
     saveWorkbook(wb, 
                  file = paste0(here::here(),  "/Output/Estado/03_Movilidad laboral/2020/Matriz MTrab por estados_2020_Reduccion_Totales.xlsx"), 
               overwrite = TRUE)
}
tabla1 <- readRDS(file = paste0(here::here(), "/Output/Estado/03_Movilidad laboral/2020/Tabla MTrab por estados.RDS"))

# Paleta de colores
#colores <- colorRampPalette(pals::inferno(100))(50)
#colores <- colorRampPalette(pals::ocean.matter(100))(100)
paleta <- colorRampPalette(c("#230A3A", "#250A3A", "#2E1047", "#2A004D", "#3B004D", "#4D004B", "#501551", "#550252", "#660762", "#7D1D6B", "#871D62","#952664", "#A6236C",  "#AF3766", "#AE2A5E", "#B53C52", "#C33B5D", "#CA3F56", "#D24949", "#DB5854", "#DE5435", "#E45B2F", "#E86328", "#ED6B21", "#ED8861", "#F4A472", "#EBB56B", "#ECC763", "#E8B94B", "#D4A432"))(50)

tabla2 <- color_chord_diagram(tabla1 = tabla1, paleta)
file = "/Graficos/Estado/03_Movilidad laboral/2020/ChordDiagram de MTrab para cada estado.pdf"

## Gráficos a nivel estatal 
chord_diagram_graph(file = file, 
                    width = 8, 
                    height = 8, 
                    family = "Montserrat Medium", 
                    paleta = paleta, 
                    tabla1 = tabla1, 
                    tabla2 = tabla2, 
                    color_labels = "#170A3A",
                    transparency = 0,
                    circo.text = 9,
                    circos.axis.text = 6,
                    adj.text =c(-0.05, 0.5), #Ajuste de las etiquetas (x, y)
                    adj.ylim = 0.1,
                    gap.degree = 2, 
                    clock.wise = FALSE,
                    track.margin = c(-0.07, 0.1),
                    margin = rep(0, 4))

Etiquetas

file = "/Graficos/Estado/03_Movilidad laboral/2020/Etiquetas a nivel estatal.pdf"

labels_chord_diagram(file = file, 
                     width = 7, 
                     height = 8, 
                     family = "Montserrat Medium", 
                     paleta = paleta, 
                     tabla1 = tabla1, 
                     labels = paste(nom_estados))

Gráfico Sankey

load(file = paste0(here::here(), "/Bases/Estado/03_Movilidad laboral/2020/Matriz de MTrab a nivel estatal 2020.RData"))

Migrantes <- Migrantes %>%
              sna::diag.remove(remove.val = 0)  

rownames(Migrantes) <- stringr::str_wrap(nom_estados, 50)
colnames(Migrantes) <- stringr::str_wrap(nom_estados, 50)

# Matiz migración laboral (Población de 15 años y más)
tabla <- Migrantes %>% 
          as.data.frame() %>%
           tibble::rownames_to_column(var = "rn") %>%
            melt(., id.vars = "rn", variable.name = "cn") %>%
             as_tibble() %>%
              mutate(rn = forcats::fct_relevel(.$rn, nom_estados),
                     cn = forcats::fct_relevel(.$cn, nom_estados)) %>%
               filter(value >= 0)  
p <- tabla %>% 
       ggplot(aes(axis1 = rn, 
                   axis2 = cn, 
                    y = value),  # c("value", "freq", "tasa")
               reverse = FALSE, 
                na.rm = TRUE) +
        geom_alluvium(aes(fill = rn),
                       curve_type = "quintic", 
                        color = "transparent", 
                         alpha = 0.85, 
                          lwd = 0.001, 
                           width = 1/5,
                            reverse = FALSE) +
          geom_stratum(aes(fill = cn), 
                        color = "white", 
                         alpha = 0.65,  
                          lwd = 0.001, 
                           width = 1/5,
                            reverse = FALSE) +
           geom_text_repel(aes(label = ifelse(after_stat(x) == 1, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""), 
                               fontface =  ifelse(after_stat(x) == 1, 'bold', 'plain')),
                            stat = "stratum", 
                             size = 3, 
                              direction = "y", 
                               nudge_x = -.2,
                                min.segment.length = unit(1, "lines"),
                                 force = 1,
                                  force_pull = 0,
                                   family = "montserrat",
                                    reverse = FALSE) +
            geom_text_repel(aes(label = ifelse(after_stat(x)  == 2, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""),
                                fontface =  ifelse(after_stat(x) == 2, 'bold', 'plain')),
                             stat = "stratum", 
                              size = 3,
                               direction = "y", 
                                nudge_x = .2, 
                                 force = 1,
                                  force_pull = 0,
                                   family = "montserrat",
                                    reverse = FALSE) +
             theme_void() + 
              theme(plot.margin = margin(t = 1, r = 1.5, b = 1, l = 0, "cm"),
                     text = element_text(family = "montserrat"),
                      axis.text = element_blank(),
                       axis.title = element_blank(),
                        strip.text = element_text(size = 10, face = "bold", family = "montserrat"),
                         legend.key.size = unit(0.5, "cm"),
                          legend.text = element_text(size = 9, family = "montserrat"),
                           legend.position = c(1, .5)) + 
               scale_x_discrete(expand = c(-0.1, 0.35)) +
                scale_fill_viridis_d(option = "A", end = 0.9, begin = 0.2) +
                 guides(fill = guide_legend(ncol = 1, na.translate = F)) + 
                  labs(fill = "", 
                       color = "")

path = paste0(here::here(), "/Graficos/Estado/03_Movilidad laboral/2020/GSankey de MTrab a nivel estatal.pdf")
ggexport(p, width = 14, height = 10, dpi = 400, filename = path)

Desagregado por estado

load(file = paste0(here::here(), "/Bases/Estado/03_Movilidad laboral/2020/Matriz de MTrab a nivel estatal 2020.RData"))

# Se cambian las equiquetas de los estados 
estados <- est 

rownames(Migrantes) <- estados
colnames(Migrantes) <- estados

tabla <- Migrantes %>%
          sna::diag.remove(remove.val = 0) %>%
           as.data.frame() %>%
            tibble::rownames_to_column(var = "rn") %>% 
             melt(., id.vars = "rn", variable.name = "cn") %>%
              mutate_if(is.factor, as.character) %>%
               mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% estados | .$cn %in% estados), value, 0)) %>%
                mutate(rn = forcats::fct_relevel(.$rn, estados),
                       cn = forcats::fct_relevel(.$cn, estados)) 
p <- lapply(1:32, function(x){
                   tabla <- tabla %>%
                             mutate(rn = forcats::fct_relevel(.$rn, estados),
                                    cn = forcats::fct_relevel(.$cn, estados)) %>%
                              mutate(value = ifelse(.$rn %in% estados[x] | .$cn %in% estados[x], value, 0)) 
 
                    tabla %>% 
                     ggplot(aes(axis1 = rn, 
                                 axis2 = cn, 
                                  y = value),  # c("value", "freq", "tasa")
                             reverse = FALSE, 
                              na.rm = TRUE) + 
                      geom_alluvium(aes(fill = rn),  
                                     color = "transparent", 
                                      alpha = 0.8, 
                                       lwd = 0.001, 
                                        width = 1/5,
                                         reverse = FALSE) +
                       geom_stratum(aes(fill = rn), 
                                     color = "#F1F1F1", 
                                      alpha = 1, 
                                       lwd = 0.001, 
                                        width = 1/5,
                                         reverse = FALSE) +
                         geom_text_repel(aes(label = ifelse(after_stat(x)  == 1, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""),
                                             fontface =  ifelse(after_stat(x) == 1, 'bold', 'plain')),
                                           stat = "stratum", 
                                            size = 3,
                                             direction = "y", 
                                              nudge_x = -.2, 
                                               force = 1,
                                                        force_pull = 0,
                                                         family = "montserrat",
                                                          reverse = FALSE) +
                          geom_text_repel(aes(label = ifelse(after_stat(x)  == 2, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""),
                                              fontface =  ifelse(after_stat(x) == 2, 'bold', 'plain')),
                                           stat = "stratum", 
                                            size = 3,
                                             direction = "y", 
                                              nudge_x = .2, 
                                               force = 1,
                                                force_pull = 0,
                                                 family = "montserrat",
                                                  reverse = FALSE) +
                            theme_void() + 
                             theme(plot.margin = margin(t = 1, r = 1.5, b = 1, l = 0, "cm"),
                                    text = element_text(family = "montserrat"),
                                     axis.text = element_blank(),
                                      axis.title = element_blank(),
                                       strip.text = element_text(size = 10, face = "bold", family = "montserrat"),
                                        legend.key.size = unit(0.5, "cm"),
                                         legend.text = element_text(size = 9, family = "montserrat"),
                                          legend.position = c(1, .5)) + 
                              scale_x_discrete(expand = c(-0.1, 0.35)) +
                               scale_fill_viridis_d(option = "A", end = 0.9, begin = 0.2) +
                                guides(fill = guide_legend(ncol = 1, na.translate = F)) + 
                                 labs(fill = "", 
                                      color = "")
              }
  )

path = paste0(here::here(),"/Graficos/Estado/03_Movilidad laboral/2020/GSankey de MTrab desagregado por estados_Absolutos.pdf")
ggexport(list = p, width = 14, height = 10, dpi = 400, filename = path)

Indicadores

Se realizan cálculos generales de migración

  • Residentes

  • Inmigrantes

  • Emigrantes

  • % Inmigrantes

  • % Emigrante

  • Migración bruta

  • Migración Neta

  • % Tasa de migración bruta

  • % Tasa de migración neta

Se trabaja con la matriz cuadrada, la cual de esta manera no se satura computacionalmente

################################################################################
############################ Población total ###################################
Pob.Total <- mydata %>%
              as.data.frame() %>%
               group_by(CVE_ENT) %>%
                summarise(Pob.Total = sum(FACTOR)) 

################################################################################
###################### Población ocupada de 15 años y más ###############################
Pob.ocupada <- mydata %>%
                as.data.frame() %>%
                 mutate(EDAD = as.numeric(.$EDAD)) %>%
                  subset((EDAD >= 15 & EDAD <= 130) & (CONACT >= 10 & CONACT <= 20)
                         ) %>%
                   group_by(CVE_ENT) %>%
                    summarise(Pob.ocupada = sum(FACTOR)) 

################################################################################
########################### Residentes #########################################
load(file = paste0(here::here(), "/Bases/Estado/03_Movilidad laboral/2020/Matriz de MTrab a nivel estatal 2020.RData"))

rownames(Migrantes) <- str_pad(rep(1:32), width = 3, pad = "0")
colnames(Migrantes) <- str_pad(rep(1:32), width = 3, pad = "0")

Residentes <- Migrantes %>%
               rownames_to_column() %>%
                tidyr::gather(CVE_ENT, Value, -rowname)%>%
                 filter(rowname == CVE_ENT) %>%
                  select(-rowname) %>%
                   droplevels() %>%
                    rename("Residentes" = "Value") 

################################################################################
############################### Inmigrantes ####################################

## Población que sale de su entidad de residencia y entra a otra demarcación por motivos laborales
Inmigrantes <- Migrantes %>% 
                sna::diag.remove(remove.val = 0) %>%
                 as.data.frame() %>%
                  tibble::rownames_to_column(var = "CVE_ENT") %>%
                   melt(., id.vars = "CVE_ENT", variable.name = "ENT_PAIS_TRAB") %>%
                    mutate_at(vars(3), as.numeric) %>%
                     as_tibble() %>%
                      filter(CVE_ENT != ENT_PAIS_TRAB) %>%
                       group_by(CVE_ENT) %>%
                        summarise(Inmigrantes = sum(value, na.rm = TRUE))

################################################################################
############################### Emigrantes #####################################

## Población que entra a la entidad para trabajar
Emigrantes <- Migrantes %>% 
               sna::diag.remove(remove.val = 0) %>%
                as.data.frame() %>%
                 tibble::rownames_to_column(var = "CVE_ENT") %>%
                  melt(., id.vars = "CVE_ENT", variable.name = "ENT_PAIS_TRAB") %>%
                   mutate_at(vars(3), as.numeric) %>%
                    as_tibble() %>%
                     filter(CVE_ENT != ENT_PAIS_TRAB) %>%
                      group_by(ENT_PAIS_TRAB) %>%
                       summarise(Emigrantes = sum(value, na.rm = TRUE)) %>%
                        rename("CVE_ENT" = "ENT_PAIS_TRAB")

tabla <- Pob.Total %>%
          left_join(., Pob.ocupada, by = c("CVE_ENT")) %>%
          left_join(., Residentes, by = c("CVE_ENT")) %>%
          left_join(., Inmigrantes, by = c("CVE_ENT")) %>%
          left_join(., Emigrantes, by = c("CVE_ENT")) %>%
            mutate(Mig.Neta = .$Inmigrantes - .$Emigrantes,
                  Mig.Bruta = .$Inmigrantes + .$Emigrantes, 
                  Tasa.Inmig = ((.$Inmigrantes/ 5) /((.$Pob.Total + .$Pob.ocupada) / 2))*1000,
                  Tasa.Emig = ((.$Emigrantes/ 5) /((.$Pob.Total + .$Pob.ocupada) / 2))*1000,
                  Tasa.Mig = Tasa.Inmig - Tasa.Emig, 
                  Eficacia = Mig.Neta - Mig.Bruta)

write.xlsx(tabla, file = paste0(here::here(), "/Output/Estado/03_Movilidad laboral/2020/Indicadores de MTrab a nivel estatal 2020.xlsx"), overwrite = TRUE)

save(tabla, file = paste0(here::here(), "/Output/Estado/03_Movilidad laboral/2020/Indicadores de MTrab a nivel estatal 2020.RData"))
Indicadores de movilidad laboral
Nivel estatal
Clave de la entidad Pob.Total Pob.ocupada Residentes Inmigrantes Emigrantes Mig.Neta Mig.Bruta Tasa.Inmig Tasa.Emig Tasa.Mig Eficacia
001 1 421 198 629 560 619 583 8 443 17 762 −9 319 26 205 1.6 3.5 −1.8 −35 524
002 3 739 797 1 765 082 1 703 754 4 410 12 192 −7 782 16 602 0.3 0.9 −0.6 −24 384
003 793 424 370 838 369 243 864 4 609 −3 745 5 473 0.3 1.6 −1.3 −9 218
004 926 858 383 130 376 224 6 452 25 999 −19 547 32 451 2.0 7.9 −6.0 −51 998
005 3 137 032 1 249 462 1 220 652 21 844 42 020 −20 176 63 864 2.0 3.8 −1.8 −84 040
006 728 300 343 548 336 327 6 476 6 410 66 12 886 2.4 2.4 0.0 −12 820
007 5 524 506 1 859 973 1 830 454 27 290 10 753 16 537 38 043 1.5 0.6 0.9 −21 506
008 3 725 058 1 599 003 1 578 018 3 973 9 005 −5 032 12 978 0.3 0.7 −0.4 −18 010
009 9 159 393 4 410 822 4 180 375 211 770 1 417 206 −1 205 436 1 628 976 6.2 41.8 −35.5 −2 834 412
010 1 821 279 687 479 648 196 37 385 17 404 19 981 54 789 6.0 2.8 3.2 −34 808
011 6 144 449 2 527 671 2 466 652 54 816 40 408 14 408 95 224 2.5 1.9 0.7 −80 816
012 3 525 695 1 301 240 1 281 383 17 868 11 421 6 447 29 289 1.5 0.9 0.5 −22 842
013 3 075 237 1 257 806 1 160 677 93 117 38 324 54 793 131 441 8.6 3.5 5.1 −76 648
014 8 303 835 3 687 695 3 639 413 40 187 50 400 −10 213 90 587 1.3 1.7 −0.3 −100 800
015 16 943 627 7 016 590 5 585 943 1 404 354 274 061 1 130 293 1 678 415 23.4 4.6 18.9 −548 122
016 4 728 162 1 913 840 1 877 152 32 061 23 038 9 023 55 099 1.9 1.4 0.5 −46 076
017 1 961 694 884 419 849 859 32 453 17 054 15 399 49 507 4.6 2.4 2.2 −34 108
018 1 226 179 515 283 500 300 12 972 11 813 1 159 24 785 3.0 2.7 0.3 −23 626
019 5 768 781 2 485 694 2 457 294 17 932 36 271 −18 339 54 203 0.9 1.8 −0.9 −72 542
020 4 113 433 1 564 801 1 539 661 21 738 18 759 2 979 40 497 1.5 1.3 0.2 −37 518
021 6 567 595 2 657 665 2 567 119 85 770 79 172 6 598 164 942 3.7 3.4 0.3 −158 344
022 2 362 209 1 042 648 1 017 122 21 087 72 385 −51 298 93 472 2.5 8.5 −6.0 −144 770
023 1 852 929 857 388 852 590 2 866 31 104 −28 238 33 970 0.4 4.6 −4.2 −62 208
024 2 815 438 1 137 612 1 115 675 18 289 22 041 −3 752 40 330 1.9 2.2 −0.4 −44 082
025 2 986 880 1 227 401 1 215 400 8 871 11 377 −2 506 20 248 0.8 1.1 −0.2 −22 754
026 2 924 652 1 228 673 1 209 493 5 386 21 618 −16 232 27 004 0.5 2.1 −1.6 −43 236
027 2 397 125 898 807 878 364 20 103 13 330 6 773 33 433 2.4 1.6 0.8 −26 660
028 3 518 497 1 472 821 1 439 916 18 841 28 358 −9 517 47 199 1.5 2.3 −0.8 −56 716
029 1 340 912 538 152 468 949 67 463 16 276 51 187 83 739 14.4 3.5 10.9 −32 552
030 8 046 861 3 137 343 3 049 368 82 256 35 784 46 472 118 040 2.9 1.3 1.7 −71 568
031 2 317 135 1 027 045 994 855 30 049 7 359 22 690 37 408 3.6 0.9 2.7 −14 718
032 1 617 384 588 193 568 818 16 942 10 615 6 327 27 557 3.1 1.9 1.1 −21 230
Fuente: Estimaciones del CONAPO.

Nivel municipal

Movilidad laboral

Matrices

### Municipios que no pertenecen en la muestra
municipios_nomuestra <- c("004012", "007125", "029048")

#Clave de los municipios 2020 
municipios <- MUN %>%
               select(CVE_MUN) %>%
                unique() %>%
                 filter(CVE_MUN %nin% municipios_nomuestra) %>%
                  pull(CVE_MUN)

Pob.ocupada <- mydata %>%
                mutate(CVE_MUN_TRABAJO = paste0(ENT_PAIS_TRAB, MUN_TRAB)) %>%
                 mutate(ENT_PAIS_TRAB = case_when(.$ENT_PAIS_TRAB %in% estados ~.$ENT_PAIS_TRAB,
                                                  .$ENT_PAIS_TRAB %nin% estados ~ "888", #Residencia en otro país
                                                  .$ENT_PAIS_TRAB %in% "997" ~ "997",
                                                  .$ENT_PAIS_TRAB %in% "998" ~ "998",
                                                  .$ENT_PAIS_TRAB %in% "997" ~ "999"),
                        CVE_MUN_TRABAJO = case_when(.$CVE_MUN_TRABAJO %in% municipios ~.$CVE_MUN_TRABAJO,
                                                    #### Se excluyen los municipios que no fueron muestreados
                                                    .$CVE_MUN_TRABAJO %in% municipios_nomuestra ~ "777",
                                                     nchar(.$CVE_MUN_TRABAJO) == 3 ~ "888",  #Municipio de trabajo en otro país
                                                    .$CVE_MUN_TRABAJO %in% "997999" ~ '997999',
                                                    .$ENT_PAIS_TRAB %in% "997" ~ "997",
                                                    .$ENT_PAIS_TRAB %in% "998" ~ "998",
                                                    .$ENT_PAIS_TRAB %in% "999" ~ "999",
                                                    .$MUN_TRAB %in% "999" ~ "999")) %>%
                  mutate(EDAD = as.numeric(.$EDAD)) %>%
                   subset((EDAD >= 15 & EDAD <= 130) & (CONACT >= 10 & CONACT <= 20) 
                          ) %>%
                    select(FACTOR, ESTRATO, UPM, CVE_MUN, CVE_MUN_TRABAJO, EDAD, CONACT) %>%
                     filter(CVE_MUN_TRABAJO %in% municipios) 

MC <- Pob.ocupada %>%
       svydesign(data = ., id = ~ UPM, strata = ~ESTRATO, weight = ~FACTOR, nest = T)

saveRDS(MC, file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2020/MC_municipal.RDS"))
MC <- readRDS(file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2020/MC_municipal.RDS"))

Migrantes <- svytable(~CVE_MUN_TRABAJO + CVE_MUN, design = MC) 

Se genera la matriz cuadrada y se le asignan los nombres de los estados.

Migrantes <- Migrantes %>%
              as.data.frame() %>%
               expss::cross_cases(CVE_MUN, CVE_MUN_TRABAJO, weight = Freq) %>%
                as.data.frame() %>%
                 rename("CVE_MUN" = "row_labels") %>% 
                  arrange(CVE_MUN) %>%
                   slice(-1) 

rownames <- Migrantes %>% 
             mutate(CVE_MUN = substr(.$CVE_MUN, 9, 16)) %>% 
              pull(CVE_MUN)

colnames <- names(Migrantes) %>% 
             as.data.frame() %>% 
              slice(-1) %>% 
               rename("CVE_MUN" = ".") %>%
                mutate(`CVE_MUN` = substr(.$CVE_MUN, 17, 22)) %>%
                 pull(CVE_MUN)

# Se elimina la variable CVE_MUN
Migrantes <- Migrantes %>%
              select(-CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

saveRDS(Migrantes, file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2020/Matriz de movilidad laboral a nivel municipal 2020.RDS"))
save(Migrantes, file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2020/Matriz de movilidad laboral a nivel municipal 2020.RData"))

require(openxlsx)
wb <- createWorkbook()
addWorksheet(wb, "M.Laboral")
writeData(wb, 1, Migrantes %>% as.data.frame() %>% tibble::rownames_to_column(var = "CVE_MUN"), colNames = TRUE)
saveWorkbook(wb, file = paste0(here::here(), "/Bases/Municipio/03_Movilidad laboral/2020/Matriz de movilidad laboral a nivel municipal 2020.xlsx"), overwrite = TRUE)

Matriz de migración laboral a nivel municipal, 2015 - 2020

Matriz de movilidad laboral
Nivel municipal
CVE_MUN 001001 001002 001003 001004 001005 001006 001007 001008 001009 001010 001011 002001 002002 002003 002004 002005 002006 003001 003002 003003 003008 003009 004001 004002 004003 004004 004005 004006 004007
001001 417985 393 600 59 6142 598 745 189 193 255 5605 0 0 0 58 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001002 3189 13007 0 12 96 63 96 0 91 30 689 0 8 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001003 351 0 19509 0 8 4 0 0 0 4 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001004 660 0 4 3765 165 64 316 20 14 0 1090 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001005 13297 31 46 55 41251 258 211 45 9 34 2088 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001006 2139 73 18 39 696 11583 572 94 358 4 3348 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001007 2771 53 10 335 433 404 16795 49 193 0 2178 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001008 282 0 2 0 48 72 9 2416 0 4 114 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001009 686 48 0 38 107 320 544 6 4357 3 1263 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001010 1656 11 6 0 5 12 0 0 0 5160 39 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001011 3732 23 8 51 806 493 111 7 66 3 21481 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
002001 27 0 0 0 0 0 0 0 0 0 0 196590 178 166 610 408 0 27 27 93 29 0 0 0 27 0 0 0 0
002002 0 0 0 0 0 0 0 0 0 0 0 251 458282 8 378 0 0 0 0 0 0 0 0 0 0 0 0 0 0
002003 0 0 0 0 0 0 0 0 0 0 0 0 98 42175 1186 0 0 0 0 0 0 0 0 0 0 0 0 0 0
002004 0 0 0 0 0 0 0 0 0 0 0 930 309 4761 888081 4766 0 520 0 0 0 0 0 0 0 0 0 0 0
002005 0 0 0 0 0 0 0 0 0 0 0 76 67 0 3690 48753 0 0 0 20 0 0 0 0 0 0 0 0 0
002006 0 0 0 0 0 0 0 0 0 0 0 0 75 0 0 0 51106 0 0 0 0 0 0 0 0 0 0 0 0
003001 0 0 0 0 0 0 0 0 0 0 0 0 7 0 0 0 0 29199 32 0 32 16 0 0 0 0 0 0 0
003002 0 0 0 0 0 0 0 0 0 0 0 101 0 0 0 0 0 12 26538 0 0 0 0 0 0 0 0 0 0
003003 0 0 0 0 0 0 0 0 0 0 0 40 0 0 107 0 0 269 120 135318 1175 0 0 0 0 0 0 0 0
003008 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 118 168522 0 0 0 0 0 0 0 0
003009 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 21 0 0 7809 0 0 0 0 0 0 0
004001 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 20497 809 262 183 394 101 36
004002 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 18 0 0 0 151 132235 923 952 227 343 19
004003 12 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 46 101786 0 0 0 0
004004 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 27 619 256 29512 0 0 0
004005 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 239 1004 159 96 9892 53 9
004006 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 162 35 25 0 14748 5
004007 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 30 0 0 0 3046
004008 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 22 605 42 26 53 22 0
Fuente: Estimaciones del CONAPO.

Gráficos

ChordDiagram

Se filtran los flujos migratorios que son exclusivos de los estados y que visualmente sean más interpretables.

# Matriz cuadrada a nivel municipal 
load(paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2020/Matriz de movilidad laboral a nivel municipal 2020.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>%
                 pull(CVE_MUN)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>%
                 pull(CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

# Nombre de los estados 
estado <- stringr::str_wrap(nom_estados, 100)

# Clave de los municipios 
### Municipios que no pertenecen en la muestra
municipios_nomuestra <- c("004012", "007125", "029048")

municipios <- MUN %>% 
               filter(CVE_MUN %nin% municipios_nomuestra) %>%
                mutate(municipios = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>%
                 pull(municipios)

################################################################################
################################## Filtro ######################################
Inmigrantes <- Inmigrantes_function(municipios, Migrantes)

Emigrantes <- Emigrantes_function(municipios, Migrantes)    

################################## Filtro ######################################
filtro  <- Inmigrantes %>%
            full_join(., Emigrantes, by = c("rn" = "cn")) %>%
             mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE))

filtro_est <- Migrantes %>%
               as.data.frame() %>%
                tibble::rownames_to_column(var = "rn") %>% 
                 melt(., id.vars = "rn", variable.name = "cn") %>%
                  mutate_if(is.factor, as.character) %>%
                   filter(value > 0)

### Sacar el promedio de los flujos migratiorios para determinar como se van a grupar los estados 
#### Es importante correr la tabla1[[x]] sin filtros para determinar el número promedio de flujos de migración
#### Filtro <<<<< filter(value > 0 & rn != estado[x]) %>%
#### Se anexa el filtro de estados filter(value > 100000000 & rn != estado[x]) %>% 
#### De esta manera solo se contemplan a los municipios
#p <- data.frame(estados = est,
 #               filtro_municipio = filtro_mig,
  #              filtro_estado = filtro_out)
#write.xlsx(p, file = paste0(here::here(), "/Bases/Municipio/03_Movilidad laboral/2020/Filtro a nivel municipal.xlsx"), overwrite = TRUE)

#### Filtro de municipios
filtro_mig <- read.xlsx(paste0(here::here(), "/Bases/Municipio/03_Movilidad laboral/2020/Filtro a nivel municipal.xlsx"), colNames = TRUE) %>%
               pull(filtro_municipio)

#### Filtro de estados 
filtro_out <- read.xlsx(paste0(here::here(), "/Bases/Municipio/03_Movilidad laboral/2020/Filtro a nivel municipal.xlsx"), colNames = TRUE) %>%
               pull(filtro_estado)

tabla <- Migrantes %>%
          as.data.frame() %>%
           tibble::rownames_to_column(var = "rn") %>%
            melt(., id.vars = "rn", variable.name = "cn") %>%
             mutate_if(is.factor, as.character) %>%
              filter(value > 0)

## Se generan los filtros correspondientes a la matriz cuadrada por estados 
tabla1 <- migration_flows_municipality(tabla = tabla, 
                                       filtro_mun = filtro,
                                       filtro_est = filtro_est,
                                       filtro_mig = filtro_mig, 
                                       filtro_out = filtro_out, 
                                       category_group = estados, 
                                       category_names = nom_estados,
                                       group_mun = "Otros municipios",
                                       group_est = "Otros estados")

## Se sacan los flujos migratorios que pertencen a otros estados
#tabla_estados <- sapply(1:32, function(i){
#                         tabla1[[i]] %>%
#                          as.data.frame() %>%
#                           adorn_totals(c("row", "col"), 
#                                         fill = "-", 
#                                          na.rm = TRUE, 
#                                           ,,,,contains(colnames(tabla1[[i]]))) %>% 
#                            select(`Otros estados`) %>%
#                             slice(nrow(.)) %>%
#                              mutate(`Otros estados` = .$`Otros estados`/4) %>%
#                               pull(`Otros estados`)
# })

## Se sacan los flujos migratorios que pertencen a otros municipios
#tabla_municipios <- sapply(1:32, function(i){
#                                   tabla1[[i]] %>%
#                                    as.data.frame() %>%
#                                     select(-c(`Otros estados`)) %>%
#                                      adorn_totals(c("row", "col"), 
#                                                    fill = "-", 
#                                                     na.rm = TRUE, 
#                                                      ,,,,contains(colnames(tabla1[[i]]))) %>% 
#                                       slice(nrow(.)) %>%
#                                        mutate(Total = .$Total/50) %>%
#                                        pull(Total)
#})

## Se guardan las matrices de movilidad laboral para analizarlos después. 
wb <- createWorkbook()
for(i in 1:32){
     tabla <- tabla1[[i]] %>%
                as.data.frame() %>%
                 adorn_totals(c("row", "col"), 
                               fill = "-", 
                                na.rm = TRUE, 
          ,,,,contains(colnames(tabla1[[i]])))
                 
     addWorksheet(wb, paste(est[i]))
     writeData(wb, i, tabla, colNames = TRUE, rowNames = TRUE)
     saveWorkbook(wb,  
                  file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2020/Matriz MTrab nivel municipal_Reduccion.xlsx"), 
               overwrite = TRUE)
}

saveRDS(tabla1, file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2020/Tabla MTrab a nivel municipal.RDS"))
tabla1 <- readRDS(file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2020/Tabla MTrab a nivel municipal.RDS"))

total_tablas <- totales(tabla1 = tabla1, 
                        Clave = "CVE_MUN", 
                        Inmigrantes = "Salen por trabajo",  
                        Emigrantes = "Entran por trabajo")

porcentajes_tablas <- porcentajes(tabla1 = tabla1, 
                                  Clave = "CVE_MUN", 
                                  Inmigrantes = "%Salen por trabajo",  
                                  Emigrantes = "%Entran por trabajo")

# Se guardan los totales de las matrices reducidas 
wb <- createWorkbook()
for(i in 1:32){
     addWorksheet(wb, paste(est[i]))
     writeData(wb, i, totales_tablas[[i]], colNames = TRUE, startCol = 1)
     writeData(wb, i, porcentajes_tablas[[i]], colNames = TRUE, startCol = 5)
     saveWorkbook(wb, 
                  file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2020/Matriz MTrab nivel municipal_Reduccion_Totales.xlsx"), 
               overwrite = TRUE)
}

Dada la magnitud de municipios en algunos estados se seleccionan solo algunos de ellos.

tabla1 <- readRDS(file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2020/Tabla MTrab a nivel municipal.RDS"))

# Paleta de colores
#colores <- colorRampPalette(pals::inferno(100))(50)
#colores <- colorRampPalette(pals::ocean.matter(100))(100)
paleta <- colorRampPalette(c("#230A3A", "#250A3A", "#2E1047", "#2A004D", "#3B004D", "#4D004B", "#501551", "#550252", "#660762", "#7D1D6B", "#871D62","#952664", "#A6236C",  "#AF3766", "#AE2A5E", "#B53C52", "#C33B5D", "#CA3F56", "#D24949", "#DB5854", "#DE5435", "#E45B2F", "#E86328", "#ED6B21", "#ED8861", "#F4A472", "#EBB56B", "#ECC763", "#E8B94B", "#D4A432"))(50)

tabla2 <- color_chord_diagram(tabla1 = tabla1, paleta)
file = "/Graficos/Municipio/03_Movilidad laboral/2020/ChordDiagram de MTrab desagregado por municipio.pdf"

## Gráficos a nivel municipal
chord_diagram_graph(file = file, 
                    width = 15, 
                    height = 10, 
                    family = "Montserrat Medium", 
                    paleta = paleta, 
                    tabla1 = tabla1, 
                    tabla2 = tabla2, 
                    color_labels = "#230A3A",
                    transparency = 0,
                    circo.text = 9,
                    circos.axis.text = 6,
                    adj.text =c(-0.05, 0.5), #Ajuste de las etiquetas (x, y)
                    adj.ylim = 0.1,
                    gap.degree = 2, 
                    clock.wise = FALSE,
                    track.margin = c(-0.07, 0.1),
                    margin = rep(0, 4))

Etiquetas

file = "/Graficos/Municipio/03_Movilidad laboral/2020/Etiquetas a nivel municipal.pdf"

labels_chord_diagram(file = file, 
                     width = 7, 
                     height = 10, 
                     family = "Montserrat Medium", 
                     paleta = paleta, 
                     tabla1 = tabla1, 
                     labels = nom_estados)

Indicadores

Se realizan cálculos generales de migración

  • Residentes

  • Inmigrantes

  • Emigrantes

  • % Inmigrantes

  • % Emigrante

  • Migración bruta

  • Migración Neta

  • % Tasa de migración bruta

  • % Tasa de migración neta

Se trabaja con la matriz cuadrada, la cual de esta manera no se satura computacionalmente

################################################################################
############################ Población total ###################################
Pob.Total <- mydata %>%
              as.data.frame() %>%
               group_by(CVE_MUN) %>%
                summarise(Pob.Total = sum(FACTOR)) 

################################################################################
############# Población ocupada de 15 años y más ###############################
Pob.ocupada <- mydata %>%
                as.data.frame() %>%
                 mutate(EDAD = as.numeric(.$EDAD)) %>%
                  subset((EDAD >= 15 & EDAD <= 130) & (CONACT >= 10 & CONACT <= 20)
                         ) %>%
                   group_by(CVE_MUN) %>%
                    summarise(Pob.ocupada = sum(FACTOR)) 

################################################################################
########################### Residentes #########################################
load(paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2020/Matriz de movilidad laboral a nivel municipal 2020.RData"))

Residentes <- Migrantes %>%
               rownames_to_column() %>%
                gather(CVE_MUN, Value, -rowname)%>%
                 filter(rowname == CVE_MUN) %>%
                  select(-rowname) %>%
                   droplevels() %>%
                    rename("Residentes" = "Value") 

################################################################################
############################### Inmigrantes ####################################

## Población que sale de su entidad de residencia y entra a otra demarcación por motivos de trabajo
Inmigrantes <- Migrantes %>% 
                as.data.frame() %>%
                 tibble::rownames_to_column(var = "CVE_MUN") %>%
                  melt(., id.vars = "CVE_MUN", variable.name = "CVE_MUN_TRABAJO") %>%
                   mutate_at(vars(3), as.numeric) %>%
                    as_tibble() %>%
                     filter(CVE_MUN != CVE_MUN_TRABAJO) %>%
                      group_by(CVE_MUN) %>%
                       summarise(Inmigrantes = sum(value, na.rm = TRUE))

################################################################################
############################### Emigrantes #####################################

## Población que entra a la entidad para trabajar
Emigrantes <- Migrantes %>% 
               as.data.frame() %>%
                tibble::rownames_to_column(var = "CVE_MUN") %>%
                 melt(., id.vars = "CVE_MUN", variable.name = "CVE_MUN_TRABAJO") %>%
                  mutate_at(vars(3), as.numeric) %>%
                   as_tibble() %>%
                    filter(CVE_MUN != CVE_MUN_TRABAJO) %>%
                     group_by(CVE_MUN_TRABAJO) %>%
                      summarise(Emigrantes = sum(value, na.rm = TRUE)) %>%
                       rename("CVE_MUN" = "CVE_MUN_TRABAJO") 

tabla <- Pob.Total %>%
         left_join(., Pob.ocupada, by = c("CVE_MUN")) %>%
         left_join(., Residentes, by = c("CVE_MUN")) %>%
         left_join(., Inmigrantes, by = c("CVE_MUN")) %>%
         left_join(., Emigrantes, by = c("CVE_MUN")) %>%
            mutate(Mig.Neta = .$Inmigrantes - .$Emigrantes,
                   Mig.Bruta = .$Inmigrantes + .$Emigrantes, 
                   Tasa.Inmig = ((.$Inmigrantes/ 5) /((.$Pob.Total + .$Pob.ocupada) / 2)) * 1000,
                   Tasa.Emig = ((.$Emigrantes/ 5) /((.$Pob.Total + .$Pob.ocupada) / 2)) * 1000,
                   Tasa.Mig = Tasa.Inmig - Tasa.Emig, 
                   Eficacia = Mig.Neta - Mig.Bruta)

write.xlsx(tabla, file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2020/Indicadores de movilidad laboral a nivel municipal 2020.xlsx"), overwrite = TRUE)

save(tabla, file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2020/Indicadores de movilidad laboral a nivel municipal 2020.RData"))
Indicadores de movilidad laboral
Nivel municipal
Clave del municipio Pob.Total Pob.ocupada Residentes Inmigrantes Emigrantes Mig.Neta Mig.Bruta Tasa.Inmig Tasa.Emig Tasa.Mig Eficacia
001001 945 506 438 864 417 985 18 980 43 036 −24 056 62 016 5.48 12.4 −7.0 −86 072
001002 51 474 17 985 13 007 4 897 1 306 3 591 6 203 28.20 7.5 20.7 −2 612
001003 58 155 20 048 19 509 463 1 001 −538 1 464 2.37 5.1 −2.8 −2 002
001004 16 997 6 337 3 765 2 544 912 1 632 3 456 43.61 15.6 28.0 −1 824
001005 129 859 58 759 41 251 17 062 8 725 8 337 25 787 36.18 18.5 17.7 −17 450
001006 47 557 19 271 11 583 7 535 2 426 5 109 9 961 45.10 14.5 30.6 −4 852
001007 57 269 23 647 16 795 6 717 2 901 3 816 9 618 33.20 14.3 18.9 −5 802
001008 9 552 2 981 2 416 538 557 −19 1 095 17.17 17.8 −0.6 −1 114
001009 22 461 7 512 4 357 3 119 1 064 2 055 4 183 41.62 14.2 27.4 −2 128
001010 20 382 7 129 5 160 1 854 702 1 152 2 556 26.96 10.2 16.7 −1 404
001011 61 986 27 027 21 481 5 475 17 066 −11 591 22 541 24.60 76.7 −52.1 −34 132
002001 440 624 200 548 196 590 1 924 2 546 −622 4 470 1.20 1.6 −0.4 −5 092
002002 1 042 395 475 210 458 282 1 988 4 623 −2 635 6 611 0.52 1.2 −0.7 −9 246
002003 102 896 45 320 42 175 1 296 5 055 −3 759 6 351 3.50 13.6 −10.1 −10 110
002004 1 910 568 937 659 888 081 12 303 11 099 1 204 23 402 1.73 1.6 0.2 −22 198
002005 126 264 55 152 48 753 3 903 5 293 −1 390 9 196 8.61 11.7 −3.1 −10 586
002006 117 050 51 193 51 106 75 0 75 75 0.18 0.0 0.2 0
003001 72 358 29 352 29 199 115 1 008 −893 1 123 0.45 4.0 −3.5 −2 016
003002 62 884 26 662 26 538 124 433 −309 557 0.55 1.9 −1.4 −866
003003 290 063 137 532 135 318 1 963 1 401 562 3 364 1.84 1.3 0.5 −2 802
Fuente: Estimaciones del CONAPO.

Movilidad Intramunicipal

Matrices

### Municipios que no pertenecen en la muestra
municipios_nomuestra <- c("004012", "007125", "029048")

#Clave de los municipios 2020 
municipios <- MUN %>%
               select(CVE_MUN) %>%
                unique() %>%
                 filter(CVE_MUN %nin% municipios_nomuestra) %>%
                  pull(CVE_MUN)

Pob.ocupada <- mydata %>%
                mutate(CVE_MUN_TRABAJO = paste0(ENT_PAIS_TRAB, MUN_TRAB)) %>%
                 mutate(ENT_PAIS_TRAB = case_when(.$ENT_PAIS_TRAB %in% estados ~.$ENT_PAIS_TRAB,
                                                  .$ENT_PAIS_TRAB %nin% estados ~ "888", #Residencia en otro país
                                                  .$ENT_PAIS_TRAB %in% "997" ~ "997",
                                                  .$ENT_PAIS_TRAB %in% "998" ~ "998",
                                                  .$ENT_PAIS_TRAB %in% "997" ~ "999"),
                        CVE_MUN_TRABAJO = case_when(.$CVE_MUN_TRABAJO %in% municipios ~.$CVE_MUN_TRABAJO,
                                                    #### Se excluyen los municipios que no fueron muestreados
                                                    .$CVE_MUN_TRABAJO %in% municipios_nomuestra ~ "777",
                                                     nchar(.$CVE_MUN_TRABAJO) == 3 ~ "888",  #Residencia en otro país
                                                    .$CVE_MUN_TRABAJO %in% "997999" ~ '997999',
                                                    .$ENT_PAIS_TRAB %in% "997" ~ "997",
                                                    .$ENT_PAIS_TRAB %in% "998" ~ "998",
                                                    .$ENT_PAIS_TRAB %in% "999" ~ "999",
                                                    .$MUN_TRAB %in% "999" ~ "999")) %>%
                  mutate(I_Migracion = case_when(.$CVE_ENT == .$ENT_PAIS_TRAB & .$ENT_PAIS_TRAB %in% estados ~ 1,
                                                 .$CVE_ENT != .$ENT_PAIS_TRAB & .$ENT_PAIS_TRAB %in% estados ~ 2,
                                                 .$ENT_PAIS_TRAB %nin% estados ~ 3)) %>%
                   mutate(EDAD = as.numeric(.$EDAD)) %>%
                    subset((EDAD >= 15 & EDAD <= 130) & (CONACT >= 10 & CONACT <= 20)) %>%
                     select(FACTOR, ESTRATO, UPM, CVE_MUN, CVE_MUN_TRABAJO, EDAD, CONACT, I_Migracion) %>%
                      filter(CVE_MUN_TRABAJO %in% municipios & I_Migracion == 1) 

MC <- Pob.ocupada %>%
       svydesign(data = ., id = ~ UPM, strata = ~ESTRATO, weight = ~FACTOR, nest = T)

saveRDS(MC, file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2020/MC_intramunicipal.RDS"))
MC <- readRDS(file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2020/MC_intramunicipal.RDS"))

Migrantes <- svytable(~CVE_MUN_TRABAJO + CVE_MUN, design = MC) 

Se genera la matriz cuadrada y se le asignan los nombres de los estados.

Migrantes <- Migrantes %>%
              as.data.frame() %>%
               expss::cross_cases(CVE_MUN, CVE_MUN_TRABAJO, weight = Freq) %>%
                as.data.frame() %>%
                 rename("CVE_MUN" = "row_labels") %>% 
                  arrange(CVE_MUN) %>%
                   slice(-1) 

rownames <- Migrantes %>% 
             mutate(CVE_MUN = substr(.$CVE_MUN, 9, 16)) %>% 
              pull(CVE_MUN)

colnames <- names(Migrantes) %>% 
             as.data.frame() %>% 
              slice(-1) %>% 
               rename("CVE_MUN" = ".") %>%
                mutate(`CVE_MUN` = substr(.$CVE_MUN, 17, 22)) %>%
                 pull(CVE_MUN)

# Se elimina la variable CVE_MUN
Migrantes <- Migrantes %>%
              select(-CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

saveRDS(Migrantes, file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2020/Matriz de movilidad laboral a nivel intramunicipal 2020.RDS"))
save(Migrantes, file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2020/Matriz de movilidad laboral a nivel intramunicipal 2020.RData"))

require(openxlsx)
wb <- createWorkbook()
addWorksheet(wb, "M.Intramunicipal")
writeData(wb, 1, Migrantes %>% as.data.frame() %>% tibble::rownames_to_column(var = "CVE_MUN"), colNames = TRUE)
saveWorkbook(wb, file = paste0(here::here(), "/Bases/Municipio/03_Movilidad laboral/2020/Matriz de movilidad laboral a nivel intramunicipal 2020.xlsx"), overwrite = TRUE)

Matriz de migración laboral a nivel municipal, 2020

Matriz de movilidad laboral
Nivel intramunicipal
CVE_MUN 001001 001002 001003 001004 001005 001006 001007 001008 001009 001010 001011 002001 002002 002003 002004 002005 002006 003001 003002 003003 003008 003009 004001 004002 004003 004004 004005 004006 004007
001001 417985 393 600 59 6142 598 745 189 193 255 5605 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001002 3189 13007 0 12 96 63 96 0 91 30 689 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001003 351 0 19509 0 8 4 0 0 0 4 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001004 660 0 4 3765 165 64 316 20 14 0 1090 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001005 13297 31 46 55 41251 258 211 45 9 34 2088 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001006 2139 73 18 39 696 11583 572 94 358 4 3348 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001007 2771 53 10 335 433 404 16795 49 193 0 2178 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001008 282 0 2 0 48 72 9 2416 0 4 114 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001009 686 48 0 38 107 320 544 6 4357 3 1263 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001010 1656 11 6 0 5 12 0 0 0 5160 39 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001011 3732 23 8 51 806 493 111 7 66 3 21481 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
002001 0 0 0 0 0 0 0 0 0 0 0 196590 178 166 610 408 0 0 0 0 0 0 0 0 0 0 0 0 0
002002 0 0 0 0 0 0 0 0 0 0 0 251 458282 8 378 0 0 0 0 0 0 0 0 0 0 0 0 0 0
002003 0 0 0 0 0 0 0 0 0 0 0 0 98 42175 1186 0 0 0 0 0 0 0 0 0 0 0 0 0 0
002004 0 0 0 0 0 0 0 0 0 0 0 930 309 4761 888081 4766 0 0 0 0 0 0 0 0 0 0 0 0 0
002005 0 0 0 0 0 0 0 0 0 0 0 76 67 0 3690 48753 0 0 0 0 0 0 0 0 0 0 0 0 0
002006 0 0 0 0 0 0 0 0 0 0 0 0 75 0 0 0 51106 0 0 0 0 0 0 0 0 0 0 0 0
003001 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 29199 32 0 32 16 0 0 0 0 0 0 0
003002 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 12 26538 0 0 0 0 0 0 0 0 0 0
003003 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 269 120 135318 1175 0 0 0 0 0 0 0 0
003008 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 118 168522 0 0 0 0 0 0 0 0
003009 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 21 0 0 7809 0 0 0 0 0 0 0
004001 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 20497 809 262 183 394 101 36
004002 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 151 132235 923 952 227 343 19
004003 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 46 101786 0 0 0 0
004004 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 27 619 256 29512 0 0 0
004005 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 239 1004 159 96 9892 53 9
004006 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 162 35 25 0 14748 5
004007 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 30 0 0 0 3046
004008 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 22 605 42 26 53 22 0
Fuente: Estimaciones del CONAPO.

Gráficos

ChordDiagram

Gráficos por estados

Se filtran los flujos migratorios que son exclusivos de los estados y que visualmente sean más interpretables.

# Matriz cuadrada a nivel municipal 
load(paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2020/Matriz de movilidad laboral a nivel intramunicipal 2020.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>%
                 pull(CVE_MUN)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>%
                 pull(CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

# Nombre de los estados 
estado <- stringr::str_wrap(nom_estados, 100)

# Clave de los municipios 
### Municipios que no pertenecen en la muestra
municipios_nomuestra <- c("004012", "007125", "029048")

municipios <- MUN %>% 
               filter(CVE_MUN %nin% municipios_nomuestra) %>%
                mutate(municipios = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>%
                 pull(municipios)

################################################################################
################################## Filtro ######################################
Inmigrantes <- Inmigrantes_function(municipios, Migrantes)

Emigrantes <- Emigrantes_function(municipios, Migrantes) 

### Sacar el promedio de los flujos migratiorios para determinar como se van a grupar los estados 
#### Es importante correr la tabla1[[x]] sin filtros para determinar el número promedio de flujos de migración
#### Filtro <<<<< filter(value > 0 & rn != estado[x]) %>%
#p <- data.frame(estados = est,
 #               filtro_municipio = filtro_mig)
#write.table(p, file = paste0(here::here(), "/Bases/Municipio/03_Movilidad laboral/2020/Filtro a nivel intramunicipal.txt"), col.names = TRUE)
#write.xlsx(p, file = paste0(here::here(), "/Bases/Municipio/03_Movilidad laboral/2020/Filtro a nivel intramunicipal.xlsx"), overwrite = TRUE)

#### Filtro de municipios
filtro_mig <- read.xlsx(paste0(here::here(), "/Bases/Municipio/03_Movilidad laboral/2020/Filtro a nivel intramunicipal.xlsx"), colNames = TRUE) %>%
               pull(filtro_municipio)

################################################################################
## Se generan los filtros correspondientes a la matriz cuadrada por estados 
tabla <- Migrantes %>%
          as.data.frame() %>%
           tibble::rownames_to_column(var = "rn") %>%
            melt(., id.vars = "rn", variable.name = "cn") %>%
             mutate_if(is.factor, as.character) %>%
              filter(value > 0)

tabla1 <- migration_flows_municipality(tabla = tabla, 
                                       filtro_mun = filtro,
                                       filtro_est = NULL,
                                       filtro_mig = filtro_mig, 
                                       filtro_out = NULL,
                                       category_group = estados, 
                                       category_names = nom_estados,
                                       group_mun = "Otros municipios",
                                       group_est = NULL)
################################################################################
## Se sacan los flujos migratorios que pertencen a otros municipios
#tabla_municipios <- sapply(1:32, function(i){
#                                  tabla1[[i]] %>%
#                                   as.data.frame() %>%
#                                    adorn_totals(c("row", "col"), 
#                                                  fill = "-", 
#                                                   na.rm = TRUE, 
#                                                    ,,,,contains(colnames(tabla1[[i]]))) %>% 
#                                    select(Total) %>%
#                                     slice(nrow(.)) %>%
#                                      mutate(Total = .$Total/100) %>%
 #}
#)

## Se guardan las matrices de movilidad laboral para analizarlos después. 
wb <- createWorkbook()
for(i in 1:32){
     tabla <- tabla1[[i]] %>%
                as.data.frame() %>%
                 adorn_totals(c("row", "col"), 
                               fill = "-", 
                                na.rm = TRUE, 
          ,,,,contains(colnames(tabla1[[i]])))
                 
     addWorksheet(wb, paste(est[i]))
     writeData(wb, i, tabla, colNames = TRUE, rowNames = TRUE)
     saveWorkbook(wb, 
                  file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2020/Matriz MTrab nivel intramunicipal_Reduccion.xlsx"), 
               overwrite = TRUE)
}
 
saveRDS(tabla1, file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2020/Tabla MTrab a nivel intramunicipal.RDS"))
tabla1 <- readRDS(file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2020/Tabla MTrab a nivel intramunicipal.RDS"))

total_tablas <- totales(tabla1 = tabla1, 
                        Clave = "CVE_MUN", 
                        Inmigrantes = "Salen por trabajo",  
                        Emigrantes = "Entran por trabajo")

porcentajes_tablas <- porcentajes(tabla1 = tabla1, 
                                  Clave = "CVE_MUN", 
                                  Inmigrantes = "%Salen por trabajo",  
                                  Emigrantes = "%Entran por trabajo")

# Se guardan los totales de las matrices reducidas 
wb <- createWorkbook()
for(i in 1:32){
     addWorksheet(wb, paste(est[i]))
     writeData(wb, i, totales_tablas[[i]], colNames = TRUE, startCol = 1)
     writeData(wb, i, porcentajes_tablas[[i]], colNames = TRUE, startCol = 5)
     saveWorkbook(wb, 
                  file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2020/Matriz MTrab nivel intramunicipal_Reduccion_Totales.xlsx"), 
               overwrite = TRUE)
}

Dada la magnitud de municipios en algunos estados se seleccionan solo algunos de ellos.

tabla1 <- readRDS(file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2020/Tabla MTrab a nivel intramunicipal.RDS"))

# Paleta de colores
#colores <- colorRampPalette(pals::inferno(100))(50)
#colores <- colorRampPalette(pals::ocean.matter(100))(100)
paleta <- colorRampPalette(c("#230A3A", "#250A3A", "#2E1047", "#2A004D", "#3B004D", "#4D004B", "#501551", "#550252", "#660762", "#7D1D6B", "#871D62","#952664", "#A6236C",  "#AF3766", "#AE2A5E", "#B53C52", "#C33B5D", "#CA3F56", "#D24949", "#DB5854", "#DE5435", "#E45B2F", "#E86328", "#ED6B21", "#ED8861", "#F4A472", "#EBB56B", "#ECC763", "#E8B94B", "#D4A432"))(50)

tabla2 <- color_chord_diagram(tabla1 = tabla1, paleta)
file = "/Graficos/Municipio/03_Movilidad laboral/2020/ChordDiagram de Mtrab desagregado a nivel intramunicipal.pdf"

## Gráficos a nivel estatal 
chord_diagram_graph(file = file, 
                    width = 15, 
                    height = 10, 
                    family = "Montserrat Medium", 
                    paleta = paleta, 
                    tabla1 = tabla1, 
                    tabla2 = tabla2, 
                    color_labels = "#230A3A",
                    transparency = 0,
                    circo.text = 9,
                    circos.axis.text = 6,
                    adj.text =c(-0.05, 0.5), #Ajuste de las etiquetas (x, y)
                    adj.ylim = 0.1,
                    gap.degree = 2, 
                    clock.wise = FALSE,
                    track.margin = c(-0.07, 0.1),
                    margin = rep(0, 4))

Etiquetas

file = "/Graficos/Municipio/03_Movilidad laboral/2020/Etiquetas a nivel intramunicipal.pdf"

labels_chord_diagram(file = file, 
                     width = 7, 
                     height = 8, 
                     family = "Montserrat Medium", 
                     paleta = paleta, 
                     tabla1 = tabla1, 
                     labels = nom_estados)

Gráfico Sankey

# Matriz cuadrada a nivel municipal 
load(paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2020/Matriz de movilidad laboral a nivel intramunicipal 2020.RData"))

tabla <- Migrantes %>%
          as.data.frame() %>%
           tibble::rownames_to_column(var = "rn") %>%
            melt(., id.vars = "rn", variable.name = "cn") %>%
             mutate_if(is.factor, as.character)

################################################################################
################################## Filtro ######################################
Inmigrantes <- Inmigrantes_function(municipios, Migrantes)

Emigrantes <- Emigrantes_function(municipios, Migrantes)   

################################## Filtro ######################################
filtro  <- Inmigrantes %>%
            full_join(., Emigrantes, by = c("rn" = "cn")) %>%
             mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
              filter(value < 0) %>% 
               pull(rn)
################################################################################

tabla1 <- lapply(1:32, function(x){
                   tabla %>%
                    mutate(rn = case_when(substr(.$rn, 1, 3) %in% estados[x] & .$rn %in% filtro ~ paste0("Otros municipios (", estados[x], ")"),
                                          substr(.$rn, 1, 3) %in% estados[x]  & .$rn %nin% filtro ~ .$rn,
                                          substr(.$rn, 1, 3) %nin% estados[x] ~ substr(.$rn, 1, 3)),
                           cn = case_when(substr(.$cn, 1, 3) %in% estados[x] & .$cn %in% filtro ~ paste0("Otros municipios (", estados[x], ")"),
                                          substr(.$cn, 1, 3) %in% estados[x] & .$cn %nin% filtro ~ .$cn,
                                          substr(.$cn, 1, 3) %nin% estados[x] ~ substr(.$cn, 1, 3))) %>%

                     mutate(value = ifelse(.$rn != .$cn, .$value, 0)) %>%
                      filter(value > 0) 
  }
)
p <- lapply(1:32, function(x){
             tabla1[[x]] %>% 
              ggplot(aes(axis1 = rn, 
                          axis2 = cn, 
                           y = value),  # c("value", "freq", "tasa")
                      reverse = FALSE, 
                       na.rm = TRUE) +
               geom_alluvium(aes(fill = rn),
                              curve_type = "quintic", 
                               color = "transparent", 
                                alpha = 0.85, 
                                 lwd = 0.001, 
                                  width = 1/5,
                                   reverse = FALSE) +
                 geom_stratum(aes(fill = cn), 
                               color = "white", 
                                alpha = 0.65,  
                                 lwd = 0.001, 
                                  width = 1/5,
                                   reverse = FALSE) +
                  geom_text_repel(aes(label = ifelse(after_stat(x) == 1, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""), 
                                       fontface =  ifelse(after_stat(x) == 1, 'bold', 'plain')),
                                   stat = "stratum", 
                                    size = 3, 
                                     direction = "y", 
                                      nudge_x = -.2,
                                       min.segment.length = unit(1, "lines"),
                                        force = 1,
                                         force_pull = 0,
                                          family = "montserrat",
                                           reverse = FALSE) +
                   geom_text_repel(aes(label = ifelse(after_stat(x)  == 2, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""),
                                        fontface =  ifelse(after_stat(x) == 2, 'bold', 'plain')),
                                    stat = "stratum", 
                                     size = 3,
                                      direction = "y", 
                                       nudge_x = .2, 
                                        force = 1,
                                         force_pull = 0,
                                          family = "montserrat",
                                           reverse = FALSE) +
                     theme_void() + 
                      theme(plot.margin = margin(t = 1, r = 5, b = 1, l = 0, "cm"),
                             text = element_text(family = "montserrat"),
                              axis.text = element_blank(),
                               axis.title = element_blank(),
                                strip.text = element_text(size = 10, face = "bold", family = "montserrat"),
                                 legend.key.size = unit(0.5, "cm"),
                                  legend.text = element_text(size = 7, family = "montserrat"),
                                   legend.position = c(1.02, .5)) + 
                       scale_x_discrete(expand = c(-0.1, 0.5)) +
                        scale_fill_viridis_d(option = "A", end = 1, begin = 0.2) +
                         guides(fill = guide_legend(ncol = 1, na.translate = F)) + 
                          labs(fill = "", 
                               color = "")
  }
)
p[[3]]
path = paste0(here::here(), "/Graficos/Municipio/03_Movilidad laboral/2020/GSankey de MR5a desagregado a nivel intramunicipal.pdf")
ggexport(list = p, width = 18, height = 10, dpi = 400, filename = path)

Indicadores

Se realizan cálculos generales de migración

  • Residentes

  • Inmigrantes

  • Emigrantes

  • % Inmigrantes

  • % Emigrante

  • Migración bruta

  • Migración Neta

  • % Tasa de migración bruta

  • % Tasa de migración neta

Se trabaja con la matriz cuadrada, la cual de esta manera no se satura computacionalmente

################################################################################
############################ Población total ###################################
Pob.Total <- mydata %>%
              as.data.frame() %>%
               group_by(CVE_MUN) %>%
                summarise(Pob.Total = sum(FACTOR)) 

################################################################################
################## Población ocupada de 15 años y más ##########################
Pob.ocupada <- mydata %>%
                as.data.frame() %>%
                 mutate(EDAD = as.numeric(.$EDAD)) %>%
                  subset((EDAD >= 15 & EDAD <= 130) & (CONACT >= 10 & CONACT <= 20)) %>%
                   group_by(CVE_MUN) %>%
                    summarise(Pob.ocupada = sum(FACTOR)) 

################################################################################
########################### Residentes #########################################
load(paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2020/Matriz de movilidad laboral a nivel intramunicipal 2020.RData"))

Residentes <- Migrantes %>%
               rownames_to_column() %>%
                gather(CVE_MUN, Value, -rowname)%>%
                 filter(rowname == CVE_MUN) %>%
                  select(-rowname) %>%
                   droplevels() %>%
                    rename("Residentes" = "Value") 

################################################################################
############################### Inmigrantes ####################################

## Población que sale de su entidad de residencia y entra a otra demarcación por motivos de trabajo
Inmigrantes <- Migrantes %>% 
                as.data.frame() %>%
                 tibble::rownames_to_column(var = "CVE_MUN") %>%
                  melt(., id.vars = "CVE_MUN", variable.name = "CVE_MUN_TRABAJO") %>%
                   mutate_at(vars(3), as.numeric) %>%
                    as_tibble() %>%
                     filter(CVE_MUN != CVE_MUN_TRABAJO) %>%
                      group_by(CVE_MUN) %>%
                       summarise(Inmigrantes = sum(value, na.rm = TRUE))

################################################################################
############################### Emigrantes #####################################

## Población que entra a la entidad para trabajar
Emigrantes <- Migrantes %>% 
               as.data.frame() %>%
                tibble::rownames_to_column(var = "CVE_MUN") %>%
                 melt(., id.vars = "CVE_MUN", variable.name = "CVE_MUN_TRABAJO") %>%
                  mutate_at(vars(3), as.numeric) %>%
                   as_tibble() %>%
                    filter(CVE_MUN != CVE_MUN_TRABAJO) %>%
                     group_by(CVE_MUN_TRABAJO) %>%
                      summarise(Emigrantes = sum(value, na.rm = TRUE)) %>%
                       rename("CVE_MUN" = "CVE_MUN_TRABAJO") 

tabla <- Pob.Total %>%
         left_join(., Pob.ocupada, by = c("CVE_MUN")) %>%
         left_join(., Residentes, by = c("CVE_MUN")) %>%
         left_join(., Inmigrantes, by = c("CVE_MUN")) %>%
         left_join(., Emigrantes, by = c("CVE_MUN")) %>%
            mutate(Mig.Neta = .$Inmigrantes - .$Emigrantes,
                   Mig.Bruta = .$Inmigrantes + .$Emigrantes, 
                   Tasa.Inmig = ((.$Inmigrantes/ 5) /((.$Pob.Total + .$Pob.ocupada) / 2)) * 1000,
                   Tasa.Emig = ((.$Emigrantes/ 5) /((.$Pob.Total + .$Pob.ocupada) / 2)) * 1000,
                   Tasa.Mig = Tasa.Inmig - Tasa.Emig, 
                   Eficacia = Mig.Neta - Mig.Bruta)

write.xlsx(tabla, file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2020/Indicadores de MTrab a nivel intramunicipal 2020.xlsx"), overwrite = TRUE)

save(tabla, file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2020/Indicadores de MTrab a nivel intramunicipal 2020.RData"))
Indicadores de movilidad laboral
Nivel intramunicipal
Clave del municipio Pob.Total Pob.ocupada Residentes Inmigrantes Emigrantes Mig.Neta Mig.Bruta Tasa.Inmig Tasa.Emig Tasa.Mig Eficacia
001001 945 506 438 864 417 985 14 779 28 763 −13 984 43 542 4.270 8.31 −4.0 −57 526
001002 51 474 17 985 13 007 4 266 632 3 634 4 898 24.567 3.64 20.9 −1 264
001003 58 155 20 048 19 509 367 694 −327 1 061 1.877 3.55 −1.7 −1 388
001004 16 997 6 337 3 765 2 333 589 1 744 2 922 39.993 10.10 29.9 −1 178
001005 129 859 58 759 41 251 16 074 8 506 7 568 24 580 34.088 18.04 16.0 −17 012
001006 47 557 19 271 11 583 7 341 2 288 5 053 9 629 43.940 13.69 30.2 −4 576
001007 57 269 23 647 16 795 6 426 2 604 3 822 9 030 31.766 12.87 18.9 −5 208
001008 9 552 2 981 2 416 531 410 121 941 16.947 13.09 3.9 −820
001009 22 461 7 512 4 357 3 015 924 2 091 3 939 40.236 12.33 27.9 −1 848
001010 20 382 7 129 5 160 1 729 337 1 392 2 066 25.139 4.90 20.2 −674
001011 61 986 27 027 21 481 5 300 16 414 −11 114 21 714 23.817 73.76 −49.9 −32 828
002001 440 624 200 548 196 590 1 362 1 257 105 2 619 0.850 0.78 0.1 −2 514
002002 1 042 395 475 210 458 282 637 727 −90 1 364 0.168 0.19 0.0 −1 454
002003 102 896 45 320 42 175 1 284 4 935 −3 651 6 219 3.465 13.32 −9.9 −9 870
002004 1 910 568 937 659 888 081 10 766 5 864 4 902 16 630 1.512 0.82 0.7 −11 728
002005 126 264 55 152 48 753 3 833 5 174 −1 341 9 007 8.451 11.41 −3.0 −10 348
002006 117 050 51 193 51 106 75 0 75 75 0.178 0.00 0.2 0
003001 72 358 29 352 29 199 80 281 −201 361 0.315 1.11 −0.8 −562
003002 62 884 26 662 26 538 12 173 −161 185 0.054 0.77 −0.7 −346
003003 290 063 137 532 135 318 1 564 118 1 446 1 682 1.463 0.11 1.4 −236
Fuente: Estimaciones del CONAPO.

Movilidad Intermunicipal

Matrices

### Municipios que no pertenecen en la muestra
municipios_nomuestra <- c("004012", "007125", "029048")

#Clave de los municipios 2020 
municipios <- MUN %>%
               select(CVE_MUN) %>%
                unique() %>%
                 filter(CVE_MUN %nin% municipios_nomuestra) %>%
                  pull(CVE_MUN)

Pob.ocupada <- mydata %>%
                mutate(CVE_MUN_TRABAJO = paste0(ENT_PAIS_TRAB, MUN_TRAB)) %>%
                 mutate(ENT_PAIS_TRAB = case_when(.$ENT_PAIS_TRAB %in% estados ~.$ENT_PAIS_TRAB,
                                                  .$ENT_PAIS_TRAB %nin% estados ~ "888", #Residencia en otro país
                                                  .$ENT_PAIS_TRAB %in% "997" ~ "997",
                                                  .$ENT_PAIS_TRAB %in% "998" ~ "998",
                                                  .$ENT_PAIS_TRAB %in% "997" ~ "999"),
                        CVE_MUN_TRABAJO = case_when(.$CVE_MUN_TRABAJO %in% municipios ~.$CVE_MUN_TRABAJO,
                                                    #### Se excluyen los municipios que no fueron muestreados
                                                    .$CVE_MUN_TRABAJO %in% municipios_nomuestra ~ "777",
                                                     nchar(.$CVE_MUN_TRABAJO) == 3 ~ "888",  #Residencia en otro país
                                                    .$CVE_MUN_TRABAJO %in% "997999" ~ '997999',
                                                    .$ENT_PAIS_TRAB %in% "997" ~ "997",
                                                    .$ENT_PAIS_TRAB %in% "998" ~ "998",
                                                    .$ENT_PAIS_TRAB %in% "999" ~ "999",
                                                    .$MUN_TRAB %in% "999" ~ "999")) %>%
                  mutate(I_Migracion = case_when(.$CVE_ENT == .$ENT_PAIS_TRAB & .$ENT_PAIS_TRAB %in% estados ~ 1,
                                                 .$CVE_ENT != .$ENT_PAIS_TRAB & .$ENT_PAIS_TRAB %in% estados ~ 2,
                                                 .$ENT_PAIS_TRAB %nin% estados ~ 3)) %>%
                   mutate(EDAD = as.numeric(.$EDAD)) %>%
                    subset((EDAD >= 15 & EDAD <= 130) & (CONACT >= 10 & CONACT <= 20)) %>%
                     select(FACTOR, ESTRATO, UPM, CVE_MUN, CVE_MUN_TRABAJO, EDAD, CONACT, I_Migracion) %>%
                      filter(CVE_MUN_TRABAJO %in% municipios & I_Migracion == 2) 

MC <- Pob.ocupada %>%
       svydesign(data = ., id = ~ UPM, strata = ~ESTRATO, weight = ~FACTOR, nest = T)

saveRDS(MC, file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2020/MC_intermunicipal.RDS"))
MC <- readRDS(file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2020/MC_intermunicipal.RDS"))

Migrantes <- svytable(~CVE_MUN_TRABAJO + CVE_MUN, design = MC) 

Se genera la matriz cuadrada y se le asignan los nombres de los estados.

Migrantes <- Migrantes %>%
              as.data.frame() %>%
               expss::cross_cases(CVE_MUN, CVE_MUN_TRABAJO, weight = Freq) %>%
                as.data.frame() %>%
                 rename("CVE_MUN" = "row_labels") %>% 
                  arrange(CVE_MUN) %>%
                   slice(-1) 

rownames <- Migrantes %>% 
             mutate(CVE_MUN = substr(.$CVE_MUN, 9, 16)) %>% 
              pull(CVE_MUN)

colnames <- names(Migrantes) %>% 
             as.data.frame() %>% 
              slice(-1) %>% 
               rename("CVE_MUN" = ".") %>%
                mutate(`CVE_MUN` = substr(.$CVE_MUN, 17, 22)) %>%
                 pull(CVE_MUN)

# Se elimina la variable CVE_MUN
Migrantes <- Migrantes %>%
              select(-CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

saveRDS(Migrantes, file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2020/Matriz de movilidad laboral a nivel intermunicipal 2020.RDS"))
save(Migrantes, file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2020/Matriz de movilidad laboral a nivel intermunicipal 2020.RData"))

require(openxlsx)
wb <- createWorkbook()
addWorksheet(wb, "M.Intermunicipal")
writeData(wb, 1, Migrantes %>% as.data.frame() %>% tibble::rownames_to_column(var = "CVE_MUN"), colNames = TRUE)
saveWorkbook(wb, file = paste0(here::here(), "/Bases/Municipio/03_Movilidad laboral/2020/Matriz de movilidad laboral a nivel intermunicipal 2020.xlsx"), overwrite = TRUE)

Matriz de migración laboral a nivel municipal, 2020

Matriz de movilidad laboral
Nivel intermunicipal
CVE_MUN 001001 001002 001003 001004 001005 001006 001007 001008 001009 001010 001011 002001 002002 002003 002004 002005 003001 003002 003003 003008 003009 004001 004002 004003 004004 004005 004006 004007 004008
001001 0 0 0 0 0 0 0 0 0 0 0 0 0 0 58 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001002 0 0 0 0 0 0 0 0 0 0 0 0 8 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001003 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001004 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001005 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001006 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001007 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001008 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001009 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001010 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001011 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
002001 27 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 27 27 93 29 0 0 0 27 0 0 0 0 0
002002 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
002003 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
002004 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 520 0 0 0 0 0 0 0 0 0 0 0 0
002005 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 20 0 0 0 0 0 0 0 0 0 0
003001 0 0 0 0 0 0 0 0 0 0 0 0 7 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
003002 0 0 0 0 0 0 0 0 0 0 0 101 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
003003 0 0 0 0 0 0 0 0 0 0 0 40 0 0 107 0 0 0 0 0 0 0 0 0 0 0 0 0 0
003008 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
003009 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
004001 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
004002 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 18 0 0 0 0 0 0 0 0 0 0 0
004003 12 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
004004 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
004005 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
004006 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
004007 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
004008 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
004009 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Fuente: Estimaciones del CONAPO.

Gráficos

ChordDiagram

Gráficos por estados

Se filtran los flujos migratorios que son exclusivos de los estados y que visualmente sean más interpretables.

# Matriz cuadrada a nivel municipal 
load(paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2020/Matriz de movilidad laboral a nivel intermunicipal 2020.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>%
                 pull(CVE_MUN)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>%
                 pull(CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

# Nombre de los estados 
estado <- stringr::str_wrap(nom_estados, 100)

# Clave de los municipios 
### Municipios que no pertenecen en la muestra
municipios_nomuestra <- c("004012", "007125", "029048")

municipios <- MUN %>% 
               filter(CVE_MUN %nin% municipios_nomuestra) %>%
                mutate(municipios = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>%
                 pull(municipios)
             
################################################################################
################################## Filtro ######################################
Inmigrantes <- Inmigrantes_function(municipios, Migrantes)

Emigrantes <- Emigrantes_function(municipios, Migrantes)   

################################## Filtro ######################################
filtro  <- Inmigrantes %>%
            full_join(., Emigrantes, by = c("rn" = "cn")) %>%
             mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
              filter(value > 0)

filtro_est <- Migrantes %>%
               as.data.frame() %>%
                tibble::rownames_to_column(var = "rn") %>% 
                 melt(., id.vars = "rn", variable.name = "cn") %>%
                  mutate_if(is.factor, as.character) %>%
                   filter(value > 0)

### Sacar el promedio de los flujos migratiorios para determinar como se van a grupar los estados 
#### Es importante correr la tabla1[[x]] sin filtros para determinar el número promedio de flujos de migración
#### Filtro <<<<< filter(value > 0 & rn != estado[x]) %>%
#p <- data.frame(estados = est,
 #               filtro_municipio = filtro_mig,
  #              filtro_estado = filtro_out)
#write.xlsx(p, file = paste0(here::here(), "/Bases/Municipio/03_Movilidad laboral/2020/Filtro a nivel intermunicipal.xlsx"), overwrite = TRUE)

#### Filtro de municipios
filtro_mig <- read.xlsx(paste0(here::here(), "/Bases/Municipio/03_Movilidad laboral/2020/Filtro a nivel intermunicipal.xlsx"), colNames = TRUE) %>%
               pull(filtro_municipio)

#### Filtro de estados 
filtro_out <- read.xlsx(paste0(here::here(), "/Bases/Municipio/03_Movilidad laboral/2020/Filtro a nivel intermunicipal.xlsx"), colNames = TRUE) %>%
               pull(filtro_estado)

################################################################################
## Se generan los filtros correspondientes a la matriz cuadrada por estados 
tabla <- Migrantes %>%
          as.data.frame() %>%
           tibble::rownames_to_column(var = "rn") %>%
            melt(., id.vars = "rn", variable.name = "cn") %>%
             mutate_if(is.factor, as.character) %>%
              filter(value > 0)

tabla1 <- migration_flows_municipality(tabla = tabla, 
                                       filtro_mun = filtro,
                                       filtro_est = filtro_est,
                                       filtro_mig = filtro_mig, 
                                       filtro_out = filtro_out, 
                                       category_group = estados, 
                                       category_names = nom_estados,
                                       group_mun = "Otros municipios",
                                       group_est = "Otros estados")
################################################################################
## Se sacan los flujos migratorios que pertencen a otros estados
#tabla_estados <- sapply(1:32, function(i){
#                                 tabla1[[i]] %>%
#                                  as.data.frame() %>%
#                                   adorn_totals(c("row", "col"), 
#                                                 fill = "-", 
#                                                  na.rm = TRUE, 
#                                                   ,,,,contains(colnames(tabla1[[i]]))) %>% 
#                                    select(`Otros estados`) %>%
#                                     slice(nrow(.)) %>%
#                                      mutate(`Otros estados` = .$`Otros estados`/10) %>%
#                                       pull(`Otros estados`)
#})


## Se sacan los flujos migratorios que pertencen a otros municipios
#tabla_municipios <- sapply(1:32, function(i){
#                               tabla1[[i]] %>%
#                                as.data.frame() %>%
#                                 select(-c(`Otros estados`)) %>%
#                                  adorn_totals(c("row", "col"), 
#                                                fill = "-", 
#                                                 na.rm = TRUE, 
#                                                  ,,,,contains(colnames(tabla1[[i]]))) %>% 
#                                    slice(nrow(.)) %>%
#                                     mutate(Total = .$Total/50) %>%
#                                      pull(Total)
#})

## Se guardan las matrices de movilidad laboral para analizarlos después. 
 wb <- createWorkbook()
for(i in 1:32){
     tabla <- tabla1[[i]] %>%
                as.data.frame() %>%
                 adorn_totals(c("row", "col"), 
                               fill = "-", 
                                na.rm = TRUE, 
          ,,,,contains(colnames(tabla1[[i]])))
                 
     addWorksheet(wb, paste(est[i]))
     writeData(wb, i, tabla, colNames = TRUE, rowNames = TRUE)
     saveWorkbook(wb, 
                  file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2020/Matriz MTrab a nivel intermunicipal_Reduccion.xlsx"), 
               overwrite = TRUE)
}
saveRDS(tabla1, file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2020/Tabla MTrab a nivel intermunicipal.RDS"))
tabla1 <- readRDS(file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2020/Tabla MTrab a nivel intermunicipal.RDS"))

total_tablas <- totales(tabla1 = tabla1, 
                        Clave = "CVE_MUN", 
                        Inmigrantes = "Salen por trabajo",  
                        Emigrantes = "Entran por trabajo")

porcentajes_tablas <- porcentajes(tabla1 = tabla1, 
                                  Clave = "CVE_MUN", 
                                  Inmigrantes = "%Salen por trabajo",  
                                  Emigrantes = "%Entran por trabajo")

# Se guardan los totales de las matrices reducidas 
wb <- createWorkbook()
for(i in 1:32){
     addWorksheet(wb, paste(est[i]))
     writeData(wb, i, totales_tablas[[i]], colNames = TRUE, startCol = 1)
     writeData(wb, i, porcentajes_tablas[[i]], colNames = TRUE, startCol = 5)
     saveWorkbook(wb, 
                  file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2020/Matriz MTrab a nivel intermunicipal_Reduccion_Totales.xlsx"), 
               overwrite = TRUE)
}

Dada la magnitud de municipios en algunos estados se seleccionan solo algunos de ellos.

tabla1 <- readRDS(file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2020/Tabla MTrab a nivel intermunicipal.RDS"))

# Paleta de colores
#colores <- colorRampPalette(pals::inferno(100))(50)
#colores <- colorRampPalette(pals::ocean.matter(100))(100)
paleta <- colorRampPalette(c("#230A3A", "#250A3A", "#2E1047", "#2A004D", "#3B004D", "#4D004B", "#501551", "#550252", "#660762", "#7D1D6B", "#871D62","#952664", "#A6236C",  "#AF3766", "#AE2A5E", "#B53C52", "#C33B5D", "#CA3F56", "#D24949", "#DB5854", "#DE5435", "#E45B2F", "#E86328", "#ED6B21", "#ED8861", "#F4A472", "#EBB56B", "#ECC763", "#E8B94B", "#D4A432"))(50)

tabla2 <- color_chord_diagram(tabla1 = tabla1, paleta)
file = "/Graficos/Municipio/03_Movilidad laboral/2020/ChordDiagram de Mtrab desagregado a nivel intermunicipal.pdf"

## Gráficos a nivel intermunicipal
chord_diagram_graph(file = file, 
                    width = 15, 
                    height = 10, 
                    family = "Montserrat Medium", 
                    paleta = paleta, 
                    tabla1 = tabla1, 
                    tabla2 = tabla2, 
                    color_labels = "#000C7D",
                    transparency = 0,
                    circo.text = 9,
                    circos.axis.text = 6,
                    adj.text =c(-0.05, 0.5), #Ajuste de las etiquetas (x, y)
                    adj.ylim = 0.1,
                    gap.degree = 2, 
                    clock.wise = FALSE,
                    track.margin = c(-0.07, 0.1),
                    margin = rep(0, 4))

Etiquetas

file = "/Graficos/Municipio/03_Movilidad laboral/2020/Etiquetas a nivel intermunicipal.pdf"

labels_chord_diagram(file = file, 
                     width = 7, 
                     height = 8, 
                     family = "Montserrat Medium", 
                     paleta = paleta, 
                     tabla1 = tabla1, 
                     labels = nom_estados)

Gráfico Sankey

# Matriz cuadrada a nivel municipal 
load(paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2020/Matriz de movilidad laboral a nivel intermunicipal 2020.RData"))

tabla <- Migrantes %>%
          as.data.frame() %>%
           tibble::rownames_to_column(var = "rn") %>%
            melt(., id.vars = "rn", variable.name = "cn") %>%
             mutate_if(is.factor, as.character)

################################################################################
################################## Filtro ######################################
Inmigrantes  <- Migrantes %>%
                 as.data.frame() %>%
                  tibble::rownames_to_column(var = "rn") %>% 
                   melt(., id.vars = "rn", variable.name = "cn") %>%
                    mutate_if(is.factor, as.character) %>%
                     mutate(value = ifelse((.$rn != .$cn) & (substr(.$rn, 1, 3) %in% estados | substr(.$cn, 1, 3) %in% estados), value, 0)) %>%
                      filter(value > 0) %>%
                       group_by(rn) %>% 
                        summarise(Inmigrantes = sum(value, na.rm = TRUE)) 

Emigrantes <- Migrantes %>%
               as.data.frame() %>%
                tibble::rownames_to_column(var = "rn") %>% 
                 melt(., id.vars = "rn", variable.name = "cn") %>%
                  mutate_if(is.factor, as.character) %>%
                   mutate(value = ifelse((.$rn != .$cn) & (substr(.$rn, 1, 3) %in% estados | substr(.$cn, 1, 3) %in% estados), value, 0)) %>%
                    filter(value > 0) %>%
                     group_by(cn) %>% 
                      summarise(Emigrantes = sum(value, na.rm = TRUE))     

################################## Filtro ######################################
filtro  <- Inmigrantes %>%
            full_join(., Emigrantes, by = c("rn" = "cn")) %>%
             mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
              filter(value < 5000) %>% 
               pull(rn)
################################################################################

tabla1 <-  lapply(1:32, function(x){
                   tabla %>%
                    mutate(rn = case_when(substr(.$rn, 1, 3) %in% estados[x] & .$rn %in% filtro ~ paste0(estados[x], " Otros municipios (", estados[x], ")"),
                                          substr(.$rn, 1, 3) %in% estados[x]  & .$rn %nin% filtro ~ .$rn,
                                          substr(.$rn, 1, 3) %nin% estados[x] ~ paste0(nom_estados[as.numeric(substr(.$rn, 1, 3))])),
                           cn = case_when(substr(.$cn, 1, 3) %in% estados[x] & .$cn %in% filtro ~ paste0(estados[x], " Otros municipios (", estados[x], ")"),
                                          substr(.$cn, 1, 3) %in% estados[x] & .$cn %nin% filtro ~ .$cn,
                                          substr(.$cn, 1, 3) %nin% estados[x] ~ paste0(nom_estados[as.numeric(substr(.$cn, 1, 3))]))) %>%
                     mutate(value = ifelse(.$rn != .$cn & (substr(.$rn, 1, 3) %in% estados[x] | substr(.$cn, 1, 3) %in% estados[x]), .$value, 0)) %>%
                      filter(value > 0)  
  }
)
p <- lapply(1:32, function(x){
             tabla1[[x]] %>% 
              ggplot(aes(axis1 = rn, 
                          axis2 = cn, 
                           y = value),  # c("value", "freq", "tasa")
                      reverse = FALSE, 
                       na.rm = TRUE) +
               geom_alluvium(aes(fill = rn),
                              curve_type = "quintic", 
                               color = "transparent", 
                                alpha = 0.85, 
                                 lwd = 0.001, 
                                  width = 1/5,
                                   reverse = FALSE) +
                 geom_stratum(aes(fill = cn), 
                               color = "white", 
                                alpha = 0.65,  
                                 lwd = 0.001, 
                                  width = 1/5,
                                   reverse = FALSE) +
                  geom_text_repel(aes(label = ifelse(after_stat(x) == 1, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""), 
                                       fontface =  ifelse(after_stat(x) == 1, 'bold', 'plain')),
                                   stat = "stratum", 
                                    size = 3, 
                                     direction = "y", 
                                      nudge_x = -.2,
                                       min.segment.length = unit(1, "lines"),
                                        force = 1,
                                         force_pull = 0,
                                          family = "montserrat",
                                           reverse = FALSE) +
                   geom_text_repel(aes(label = ifelse(after_stat(x)  == 2, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""),
                                        fontface =  ifelse(after_stat(x) == 2, 'bold', 'plain')),
                                    stat = "stratum", 
                                     size = 3,
                                      direction = "y", 
                                       nudge_x = .2, 
                                        force = 1,
                                         force_pull = 0,
                                          family = "montserrat",
                                           reverse = FALSE) +
                     theme_void() + 
                      theme(plot.margin = margin(t = 1, r = 5, b = 1, l = 0, "cm"),
                             text = element_text(family = "montserrat"),
                              axis.text = element_blank(),
                               axis.title = element_blank(),
                                strip.text = element_text(size = 10, face = "bold", family = "montserrat"),
                                 legend.key.size = unit(0.5, "cm"),
                                  legend.text = element_text(size = 7, family = "montserrat"),
                                   legend.position = c(1.02, .5)) + 
                       scale_x_discrete(expand = c(-0.1, 0.5)) +
                        scale_fill_viridis_d(option = "A", end = 1, begin = 0.2) +
                         guides(fill = guide_legend(ncol = 1, na.translate = F)) + 
                          labs(fill = "", 
                               color = "")
  }
)

path = paste0(here::here(), "/Graficos/Municipio/03_Movilidad laboral/2020/GSankey de MR5a desagregado a nivel intermunicipal.pdf")
ggexport(list = p, width = 18, height = 10, dpi = 400, filename = path)

Indicadores

Se realizan cálculos generales de migración

  • Residentes

  • Inmigrantes

  • Emigrantes

  • % Inmigrantes

  • % Emigrante

  • Migración bruta

  • Migración Neta

  • % Tasa de migración bruta

  • % Tasa de migración neta

Se trabaja con la matriz cuadrada, la cual de esta manera no se satura computacionalmente

################################################################################
############################ Población total ###################################
Pob.Total <- mydata %>%
              as.data.frame() %>%
               group_by(CVE_MUN) %>%
                summarise(Pob.Total = sum(FACTOR)) 

################################################################################
################## Población ocupada de 15 años y más ##########################
Pob.ocupada <- mydata %>%
                as.data.frame() %>%
                 mutate(EDAD = as.numeric(.$EDAD)) %>%
                  subset((EDAD >= 15 & EDAD <= 130) & (CONACT >= 10 & CONACT <= 20)) %>%
                   group_by(CVE_MUN) %>%
                    summarise(Pob.ocupada = sum(FACTOR)) 

################################################################################
########################### Residentes #########################################
load(paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2020/Matriz de movilidad laboral a nivel intermunicipal 2020.RData"))

Residentes <- Migrantes %>%
               rownames_to_column() %>%
                gather(CVE_MUN, Value, -rowname)%>%
                 filter(rowname == CVE_MUN) %>%
                  select(-rowname) %>%
                   droplevels() %>%
                    rename("Residentes" = "Value") 

################################################################################
############################### Inmigrantes ####################################
Inmigrantes <- Migrantes %>% 
                as.data.frame() %>%
                 tibble::rownames_to_column(var = "CVE_MUN") %>%
                  melt(., id.vars = "CVE_MUN", variable.name = "CVE_MUN_TRABAJO") %>%
                   mutate_at(vars(3), as.numeric) %>%
                    as_tibble() %>%
                     filter(CVE_MUN != CVE_MUN_TRABAJO) %>%
                      group_by(CVE_MUN) %>%
                       summarise(Inmigrantes = sum(value, na.rm = TRUE))

################################################################################
############################### Emigrantes #####################################
Emigrantes <- Migrantes %>% 
               as.data.frame() %>%
                tibble::rownames_to_column(var = "CVE_MUN") %>%
                 melt(., id.vars = "CVE_MUN", variable.name = "CVE_MUN_TRABAJO") %>%
                  mutate_at(vars(3), as.numeric) %>%
                   as_tibble() %>%
                    filter(CVE_MUN != CVE_MUN_TRABAJO) %>%
                     group_by(CVE_MUN_TRABAJO) %>%
                      summarise(Emigrantes = sum(value, na.rm = TRUE)) %>%
                       rename("CVE_MUN" = "CVE_MUN_TRABAJO") 

tabla <- Pob.Total %>%
         left_join(., Pob.ocupada, by = c("CVE_MUN")) %>%
         left_join(., Residentes, by = c("CVE_MUN")) %>%
         left_join(., Inmigrantes, by = c("CVE_MUN")) %>%
         left_join(., Emigrantes, by = c("CVE_MUN")) %>%
            mutate(Mig.Neta = .$Inmigrantes - .$Emigrantes,
                   Mig.Bruta = .$Inmigrantes + .$Emigrantes, 
                   Tasa.Inmig = ((.$Inmigrantes/ 5) /((.$Pob.Total + .$Pob.ocupada) / 2)) * 1000,
                   Tasa.Emig = ((.$Emigrantes/ 5) /((.$Pob.Total + .$Pob.ocupada) / 2)) * 1000,
                   Tasa.Mig = Tasa.Inmig - Tasa.Emig, 
                   Eficacia = Mig.Neta - Mig.Bruta)

write.xlsx(tabla, file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2020/Indicadores de MTrab a nivel intermunicipal 2020.xlsx"), overwrite = TRUE)

save(tabla, file = paste0(here::here(), "/Output/Municipio/03_Movilidad laboral/2020/Indicadores de MTrab a nivel intermunicipal 2020.RData"))
Indicadores de movilidad laboral
Nivel intermunicipal
Clave del municipio Pob.Total Pob.ocupada Residentes Inmigrantes Emigrantes Mig.Neta Mig.Bruta Tasa.Inmig Tasa.Emig Tasa.Mig Eficacia
001001 945 506 438 864 0 4 201 14 273 −10 072 18 474 1.214 4.12 −2.9 −28 546
001002 51 474 17 985 0 631 674 −43 1 305 3.634 3.88 −0.2 −1 348
001003 58 155 20 048 0 96 307 −211 403 0.491 1.57 −1.1 −614
001004 16 997 6 337 0 211 323 −112 534 3.617 5.54 −1.9 −646
001005 129 859 58 759 0 988 219 769 1 207 2.095 0.46 1.6 −438
001006 47 557 19 271 0 194 138 56 332 1.161 0.83 0.3 −276
001007 57 269 23 647 0 291 297 −6 588 1.439 1.47 0.0 −594
001008 9 552 2 981 0 7 147 −140 154 0.223 4.69 −4.5 −294
001009 22 461 7 512 0 104 140 −36 244 1.388 1.87 −0.5 −280
001010 20 382 7 129 0 125 365 −240 490 1.817 5.31 −3.5 −730
001011 61 986 27 027 0 175 652 −477 827 0.786 2.93 −2.1 −1 304
002001 440 624 200 548 0 562 1 289 −727 1 851 0.351 0.80 −0.5 −2 578
002002 1 042 395 475 210 0 1 351 3 896 −2 545 5 247 0.356 1.03 −0.7 −7 792
002003 102 896 45 320 0 12 120 −108 132 0.032 0.32 −0.3 −240
002004 1 910 568 937 659 0 1 537 5 235 −3 698 6 772 0.216 0.74 −0.5 −10 470
002005 126 264 55 152 0 70 119 −49 189 0.154 0.26 −0.1 −238
002006 117 050 51 193 0 0 0 0 0 0 0 0 0
003001 72 358 29 352 0 35 727 −692 762 0.138 2.86 −2.7 −1 454
003002 62 884 26 662 0 112 260 −148 372 0.500 1.16 −0.7 −520
003003 290 063 137 532 0 399 1 283 −884 1 682 0.373 1.20 −0.8 −2 566
Fuente: Estimaciones del CONAPO.

Referencias

Librerias que se usaron en el documento

package loadedversion source
Cairo 1.6-1 CRAN (R 4.3.1)
chorddiag 0.1.3 Github ()
circlize 0.4.15 CRAN (R 4.3.1)
doMC 1.3.5 R-Forge (R 4.3.1)
dplyr 1.1.3 CRAN (R 4.3.2)
expss 0.11.6 CRAN (R 4.3.1)
foreach 1.5.2 CRAN (R 4.3.1)
ggalluvial 0.12.5 CRAN (R 4.3.1)
ggplot2 3.4.3 CRAN (R 4.3.1)
ggpubr 0.6.0 CRAN (R 4.3.1)
ggrepel 0.9.3 CRAN (R 4.3.1)
ggsankey 0.0.99999 Github ()
gt 0.10.0 CRAN (R 4.3.1)
haven 2.5.3 CRAN (R 4.3.1)
Hmisc 5.1-0 CRAN (R 4.3.1)
iterators 1.0.14 CRAN (R 4.3.1)
janitor 2.2.0 CRAN (R 4.3.1)
kableExtra 1.3.4 CRAN (R 4.3.1)
knitr 1.45 CRAN (R 4.3.2)
maditr 0.8.3 CRAN (R 4.3.1)
mapview 2.11.0 CRAN (R 4.3.1)
Matrix 1.6-1.1 CRAN (R 4.3.1)
network 1.18.1 CRAN (R 4.3.1)
openxlsx 4.2.5.2 CRAN (R 4.3.1)
reshape2 1.4.4 CRAN (R 4.3.1)
sjlabelled 1.2.0 CRAN (R 4.3.1)
sna 2.7-1 CRAN (R 4.3.1)
srvyr 1.2.0 CRAN (R 4.3.1)
statnet.common 4.9.0 CRAN (R 4.3.1)
stringr 1.5.0 CRAN (R 4.3.1)
survey 4.2 Github ()
survival 3.5-5 CRAN (R 4.3.1)
tibble 3.2.1 CRAN (R 4.3.1)
tidyr 1.3.1 CRAN (R 4.3.3)

Creative Commons Licence
This work by Diana Villasana Ocampo is licensed under a Creative Commons Attribution 4.0 International License.